简体   繁体   中英

Test partial object properties with Chai's Expect interface

I have an object with many properties and want to check some of them. But one of the fields is a random string so that cannot be checked for an exact match.

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

Checking with eql doesn't work due to the random field.

expect(result).to.eql(expectedObject)

Is there a similar method where I can provide an object with only the fields I want to test?

The alternative is to delete the random field for the test, but this is a bit cumbersome.

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)

.containSubset() method of chai-subset plugin. Partial matching can be performed on the fields in the object.

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');
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM