使用 Chai 的 Expect 接口测试部分对象属性

问题描述 投票:0回答:2

我有一个具有许多属性的对象,想要检查其中一些属性。但其中一个字段是随机字符串,因此无法检查精确匹配。

const expectedObject = {
  a: 'A',
  b: 123,
  c: ['x', 'y', 'z'],
  random: 'dsfgshdfsg'
}

由于随机场,使用

eql
检查不起作用。

expect(result).to.eql(expectedObject)

是否有类似的方法可以提供仅包含我想要测试的字段的对象?

替代方法是删除测试的随机字段,但这有点麻烦。

const resultWithKnownFields = {...result}
delete resultWithKnownFields.random
const expectedObject = {
  a: 'A',
  b: 123,
  c: ['x', 'y', 'z']
}
expect(resultWithKnownFields).to.eql(expectedObject)
expect(result.random.length).to.equal(10)
javascript unit-testing chai
2个回答
1
投票

.containSubset()
chai-subset 插件的方法。 可以对对象中的字段进行部分匹配。

const { expect } = require('chai');
const chai = require('chai');
const chaiSubset = require('chai-subset');
chai.use(chaiSubset);

describe('69555042', () => {
  it('should pass', () => {
    const expectedObject = {
      a: 'A',
      b: 123,
      c: ['x', 'y', 'z'],
    };
    const result = {
      a: 'A',
      b: 123,
      c: ['x', 'y', 'z'],
      random: 'dsfgshdfsg',
    };
    expect(result).to.containSubset(expectedObject);
    expect(typeof result.random).to.equal('string');
  });
});

0
投票

无需插件即可使用的另一个选项是使用扩展语法来使用原始对象生成新对象。这样,任何您不关心的值都会以相等的方式开始,并且在比较中被有效地忽略。

expect(result).to.eql({
  ...result,
  a: 'A',
  b: 123,
  c: ['x', 'y', 'z']
  // 'random' would have the same value as result
});

如果你想测试嵌套成员,它确实会变得有点麻烦,因为你必须分散每个成员。

expect(result).to.eql({
  a: 'A',
  nestedObject: {
    ...result.nestedObject,
    nestedProperty: 'whatever'
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.