Skip to content

Instantly share code, notes, and snippets.

@bignimbus
Created October 3, 2017 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bignimbus/22b5f354e9ee26128cc9f71827bedc15 to your computer and use it in GitHub Desktop.
Save bignimbus/22b5f354e9ee26128cc9f71827bedc15 to your computer and use it in GitHub Desktop.
Async unit tests with Jest
const INTERVAL = 100;
function myFunction () {
setTimeout(() => {
console.log('hi');
}, INTERVAL);
}
describe('myFunction', () => {
it('should be testable', () => {
// spy on console.log
console.log = jest.fn();
// instructs Jest to fail the test if the number of `expect` invocations in the
// block beneath this expression does not equal the argument provided
expect.assertions(1);
// adding a return statement with a Promise tells Jest not to terminate this spec
// until the Promise is resolved or rejected
return new Promise((res) => {
myFunction();
// JavaScript's clock isn't 100% precise, let's give 50ms of wiggle room
setTimeout(res, INTERVAL + 50);
})
.then(() => {
expect(console.log).toHaveBeenCalledWith('hi');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment