【问题标题】:Chai check that an array includes an object that includes keysChai 检查一个数组是否包含一个包含键的对象
【发布时间】:2017-10-27 14:27:36
【问题描述】:

我在使用 Chai 进行集成测试时遇到问题。我想检查一个数组是否包含一个包含一些键的对象。在这种情况下,我正在向用户添加一个地址,并且我希望检查当用户返回时,地址数组是否包含我最初传递的字段,但没有检查 MongoDB 生成的ObjectId。我一直在使用chai things 进行数组操作。

当我知道我正在检查的元素位于索引 0 处时,我有一个可行的解决方案,格式如下:

expect(response.body.addresses[0]).to.deep.include({
                text: '123, fake street',
                loc: {
                    type: 'Point',
                    coordinates: [0, 0]
                }
});

我想要的是利用chai-things 断言该数组包含一个满足与上述断言相同要求的对象。我能想出的最接近的解决方案是:

expect(response.body.addresses).to.contain.something.that.deep.includes({
                  text: '123, fake street',
                  loc: {
                      type: 'Point',
                      coordinates: [0, 0]
                  }
});

但这失败了:AssertionError: expected { Object (text, _id, ...) } to deep include { text: '123, fake street', loc: { type: 'Point', coordinates: [ 0, 0 ] } }

有没有办法在不依赖于对象在数组中的位置的情况下实现这一点?

【问题讨论】:

    标签: mocha.js chai


    【解决方案1】:

    我也尝试使用 chai-things 来解决这个问题,但无法做到。最终使用chai-subset

    在您的测试设置中:

    chai.use(require('chai-subset'))

    在测试中

    expect(response.body.addresses).to.containSubset([{
      text: '123, fake street',
      loc: {
        type: 'Point',
        coordinates: [0, 0]
      }
    }])
    

    【讨论】:

      猜你喜欢
      • 2020-08-11
      • 2018-07-21
      • 2016-04-24
      • 2020-11-29
      • 2021-12-21
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多