问题描述
我有一个验证器方法,它返回一个包含错误的数组。我想创建一个比较这些错误的单元测试,但我不能使用 expect(fn).to.throw
,因为我不抛出错误,只是返回它们。
这是我的方法,但我得到 AssertionError: expected [ Array(2) ] to have the same members as [ Array(2) ]
it.only('catches when first row is a single-column',function () {
const worksheet = readWorksheet(Buffer.from(
'Table 1\n' +
'action,Email,firstname,lastname,channelIds\n' +
'save,[email protected],foo,bar,00000A'
))
const errors = validateHeaderRow(worksheet,requiredColumnNames,columnAliases)
expect(errors).to.have.same.members([
new Error('Missing required column/s action'),new Error('The column label "Table 1" is invalid'),])
})
以前我们使用 Jasmine .toEqual
有效,但现在我们改用 Mocha-Chai-Sinon,我无法让它工作。
解决方法
由于 Error 对象有许多属性并且比较起来不是那么简单,我会通过映射每个 Error 对象的 message
属性并与之比较来使问题更容易。断言变为:
expect(errors.map((err) => err.message)).to.deep.equal([
'Missing required column/s action','The column label "Table 1" is invalid',]);
此解决方案验证我们的 Errors 数组是否包含我们期望的每个 Error 对象。