我正在使用Jest为React应用程序编写测试,但我无法弄清楚如何为自定义错误消息编写单元测试期望案例。我试图编写测试的函数是:
export function maxSixCharacters(path, state, value) {
if (value && String(value).length > 6) {
throw new ValidationError("Cannot be more than 6 characters")
}
return true
}
ValidationError
扩展了Error
类:
export class ValidationError extends Error {
isValidationError = true
constructor(message, errorMessage=undefined, secondaryCopy=undefined, ...args) {
super(message, ...args)
if (errorMessage !== undefined) {
this.errorMessage = errorMessage
} else {
this.errorMessage = message
}
if (secondaryCopy !== undefined) {
this.secondaryCopy = secondaryCopy
}
}
}
我想写这样的东西:
describe('maxSixCharacters', () => {
it('should throw an error if more than 6 characters', () => {
expect(maxSixCharacters('', {}, '12345678')).toThrow('Cannot be more than 6 characters')
})
})
然而,这失败了。我如何编写测试用例以使其通过?
答案 0 :(得分:1)
如docs所述,您需要在expect
声明中模拟它的调用:
从以下位置更改:
expect(maxSixCharacters('', {}, '12345678')).toThrow('Cannot be more than 6 characters')
为:
expect(() => maxSixCharacters('', {}, '12345678')).toThrow('Cannot be more than 6 characters')