2019-11-18
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:
1
2
3
4
5
6
7
8
9
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:
1
2
3
4
5
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:
1
2
3
4
5
it ("should reject when no name is passed" , () => {
return greeter ().catch ( err => {
expect (err ).toEqual ("Empty name" )
})
})