问题
I have a function like this:
const test = (match) => {
if (match !== 'cat') {
throw new TypeError()
}
}
My test would be:
describe('test', () => {
it('must throw error'() => {
try {
test('cat')
catch(err){
expect(err).toStrictEqual(new TypeError())
}
}
}
But the test passed. It should fail. Why did it pass?
回答1:
Tests only fail if there is an unmet expectation. In your case, because no error is thrown, no expectation is ever even evaluated. Therefore the test passes.
To deal with this, either:
make sure exactly one expectation is evaluated using expect.assertions:
describe('test', () => { it('must throw error'() => { expect.assertions(1); try { test('cat') catch(err){ expect(err).toStrictEqual(new TypeError()) } } }
or
handle the error with a .toThrow expectation rather than catching it yourself:
describe('test', () => { it('must throw error'() => { expect(() => test('cat')).toThrow(TypeError) } }
Note that, as Estus Flask pointed out, this can only assert on either the constructor or the message of the error.
来源:https://stackoverflow.com/questions/64330421/why-does-jest-throw-an-error-when-it-should-not