Skip to content

Instantly share code, notes, and snippets.

@geotrev
Last active January 10, 2020 17:30
Show Gist options
  • Save geotrev/0133cd3d8cee1796248c4ac864c4991e to your computer and use it in GitHub Desktop.
Save geotrev/0133cd3d8cee1796248c4ac864c4991e to your computer and use it in GitHub Desktop.
timer mock
const mockTimers = () => {
	const globalTimerFn = window.setTimeout;

	const runAllTimers = () => (window.setTimeout = (fn) => fn());
	const restoreAllTimers = () => (window.setTimeout = globalTimerFn);

	return {runAllTimers, restoreAllTimers};
};

describe('mockTimers', () => {
	let delayedReceived = false;
	let mock = mockTimers();
	
	const assignToDelayedReceived = (ms = 3000) => {
			setTimeout(() => (delayedReceived = true), ms);
		};

	afterEach(() => {
		delayedReceived = false;
		mock.restoreAllTimers();
	});

	it('runAllTimers: runs all timers immediately', () => {
		mock.runAllTimers();
		
		assignToDelayedReceived();
		assert.equal(delayedReceived, true);
	});

	it('restoreAllTimers: restores default setTimeout', async () => {
		mock.runAllTimers();
		mock.restoreAllTimers();
		assignToDelayedReceived(1500);
		assert.equal(delayedReceived, false);

		// test that the timeout resolved after 1500ms
		await new Promise((done) => setTimeout(done, 1500));
		assert.equal(delayedReceived, true);
	});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment