Error: expect(received).toThrow()
Received function did not throw
async function foo (a, b) {
if (a == null || b == null) {
throw new TypeError()
}
return new Promise((resolve, reject) => {
// do something
resolve('success')
})
}
describe('something', () => {
it('should throw error', () => {
expect(() => foo()).toThrow()
})
})
This test should pass
npx envinfo --preset jest System:
OS: Windows 10
CPU: (4) x64 Intel(R) Core(TM) i7-7660U CPU @ 2.50GHz
Binaries:
Node: 11.12.0 - C:\Program Files\nodejs\node.EXE
Yarn: 1.15.2 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 6.7.0 - C:\Program Files\nodejs\npm.CMD
When you throw an Error in an async function, the error is automatically caught and used to reject the Promise. Promise rejection is not the same thing as an Error being thrown, although I understand why it's confusing since async methods can be caught with try/catch.
@scotthovestadt
thanks for helping
Most helpful comment
When you throw an Error in an async function, the error is automatically caught and used to reject the Promise. Promise rejection is not the same thing as an Error being thrown, although I understand why it's confusing since
asyncmethods can be caught with try/catch.See:
https://jestjs.io/docs/en/tutorial-async#rejects