在JavaScript中对自定义错误消息进行单元测试

时间:2018-01-17 19:09:47

标签: javascript reactjs unit-testing jestjs

我正在使用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')
  })
})

然而,这失败了。我如何编写测试用例以使其通过?

1 个答案:

答案 0 :(得分:1)

docs所述,您需要在expect声明中模拟它的调用:

从以下位置更改:

expect(maxSixCharacters('', {}, '12345678')).toThrow('Cannot be more than 6 characters')

为:

expect(() => maxSixCharacters('', {}, '12345678')).toThrow('Cannot be more than 6 characters')