Home > Back-end >  Test partial object properties with Chai's Expect interface
Test partial object properties with Chai's Expect interface

Time:10-15

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)

CodePudding user response:

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