Chai 检查数组是否包含包含键的对象

Chai check that an array includes an object that includes keys

我在使用 Chai 进行集成测试时遇到问题。我想检查一个数组是否包含一个包含一些键的对象。在这种情况下,我向用户添加了一个地址,我希望检查当用户返回时,地址数组是否包含我最初传递的字段,但不检查 [=26= 生成的 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 ] } }

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

我也尝试使用 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]
  }
}])