Testing asynchronous functions with Jest
Because I seem to have a mental block when it comes to remembering the syntax for testing asynchronous promised-based Javascript functions with Jest, here's a reminder to self:
Assuming a function like:
const greeter = (name) => {
return new Promise( (resolve, reject) => {
if (!name) {
reject("Empty name")
return
}
resolve("Hello, " + name)
})
}
This will need two tests - the happy path, which is straight-forward:
it("should greet when provided with a name", () => {
return greeter("foo").then( response => {
expect(response).toEqual("Hello, foo")
})
})
And the unhappy path, which needs the error to be caught and checked:
it("should reject when no name is passed", () => {
return greeter().catch( err => {
expect(err).toEqual("Empty name")
})
})