【问题标题】:Compare arrays of Errors in Chai比较 Chai 中的错误数组
【发布时间】:2021-04-01 11:08:03
【问题描述】:

我有一个验证器方法,它返回一个带有错误的数组。我想创建一个单元测试来比较这个错误,但我不能使用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,foo@example.com,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,我无法让它工作。

【问题讨论】:

    标签: javascript arrays mocha.js chai sinon


    【解决方案1】:

    由于 Error 对象有很多属性并且比较不那么简单,我会通过从每个 Error 对象映射 message 属性并与之进行比较来简化问题。断言变为:

    expect(errors.map((err) => err.message)).to.deep.equal([
        'Missing required column/s action',
        'The column label "Table 1" is invalid',
    ]);
    

    此解决方案验证我们的错误数组是否包含我们期望的每个错误对象。

    【讨论】:

      猜你喜欢
      • 2016-02-17
      • 2020-02-26
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多