From e4e2c24407760d3ee2717bc2544c5bda8fa9fec6 Mon Sep 17 00:00:00 2001 From: Rune Harlyk Date: Fri, 23 Feb 2024 12:22:00 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=AA=20Adds=20test=20for=20throttle=20c?= =?UTF-8?q?lass?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/test/specs/throttler.spec.ts | 46 ++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 app/test/specs/throttler.spec.ts diff --git a/app/test/specs/throttler.spec.ts b/app/test/specs/throttler.spec.ts new file mode 100644 index 0000000..ec89eac --- /dev/null +++ b/app/test/specs/throttler.spec.ts @@ -0,0 +1,46 @@ +import { throttler } from '../../src/lib/utilities'; +import { describe, it, expect, beforeEach, afterEach, test, vitest } from 'vitest'; + +describe('throttler', () => { + let throttleInstance: throttler; + let callback + + beforeEach(() => { + vitest.useFakeTimers(); + throttleInstance = new throttler(); + callback = vitest.fn(); + }); + + afterEach(() => { + vitest.useRealTimers(); + }); + + it('should call the callback function after the specified time', () => { + throttleInstance.throttle(callback, 1000); + expect(callback).not.toHaveBeenCalled(); + + vitest.advanceTimersByTime(1000); + expect(callback).toHaveBeenCalledTimes(1); + }); + + it('should not call the callback function if throttle is called again within the timeout period', () => { + throttleInstance.throttle(callback, 1000); + throttleInstance.throttle(callback, 1000); + + vitest.advanceTimersByTime(500); + expect(callback).not.toHaveBeenCalled(); + + vitest.advanceTimersByTime(500); + expect(callback).toHaveBeenCalledTimes(1); + }); + + it('should allow the callback to be called again after the timeout period', () => { + throttleInstance.throttle(callback, 1000); + vitest.advanceTimersByTime(1000); + expect(callback).toHaveBeenCalledTimes(1); + + throttleInstance.throttle(callback, 1000); + vitest.advanceTimersByTime(1000); + expect(callback).toHaveBeenCalledTimes(2); + }); +}); \ No newline at end of file