我正在使用 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')
})
})
但是,这失败了。我该如何编写测试用例才能使其通过?
最佳答案
正如 docs 中所述,您需要在 expect
语句中模拟它的调用:
将其更改为:
expect(maxSixCharacters('', {}, '12345678')).toThrow('Cannot be more than 6 characters')
至:
expect(() => maxSixCharacters('', {}, '12345678')).toThrow('Cannot be more than 6 characters')
关于javascript - JavaScript 中自定义错误消息的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48308311/