Created
October 3, 2017 15:57
-
-
Save bignimbus/22b5f354e9ee26128cc9f71827bedc15 to your computer and use it in GitHub Desktop.
Async unit tests with Jest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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