Match partial objects in Chai assertions?

前端 未结 8 2067
谎友^
谎友^ 2021-01-07 18:07

I am looking for the best way to match the following:

expect([
    {
        C1: \'xxx\',
        C0: \'this causes it not to match.\'
    }
]).to.deep.incl         


        
相关标签:
8条回答
  • 2021-01-07 18:25

    I believe the simplest (and certainly easiest) way would be to:

    var actual=[
      {
        C1:'xxx',
        C0:'yyy'
      }
    ];
    
    actual.forEach(function(obj){
      expect(obj).to.have.property('C1','xxx');
    });
    
    0 讨论(0)
  • 2021-01-07 18:25

    I wrote chai-match-pattern and lodash-match-pattern to handle partial matching (and many more) deep matching scenarios.

    var chai = require('chai');
    var chaiMatchPattern = require('chai-match-pattern');
    chai.use(chaiMatchPattern);
    
    // Using JDON pattern in expectation
    chai.expect([
      {
        C1: 'xxx',
        C0: 'this causes it not to match.'
      }
    ]).to.matchPattern([
      {
        C1: 'xxx',
        '...': ''
      }
    ]);
    
    // Using the slightly cleaner string pattern notation in expectation
    chai.expect([
      {
        C1: 'xxx',
        C0: 'this causes it not to match.'
      }
    ]).to.matchPattern(`
      [
        {
          C1: 'xxx',
          ...
        }
      ]
      `
    );
    
    0 讨论(0)
  • 2021-01-07 18:27

    without plugins: http://chaijs.com/api/bdd/#method_property

      expect([
        {
          C1: 'xxx',
          C0: 'this causes it not to match.'
        }
      ]).to.have.deep.property('[0].C1', 'xxx');
    
    0 讨论(0)
  • 2021-01-07 18:34

    There are a few different chai plugins which all solve this problem. I am a fan of shallow-deep-equal. You'd use it like this:

    expect([
        {
          C1: 'xxx',
          C0: 'this causes it not to match.'
        }
      ]).to.shallowDeepEqual([
        {
          C1: 'xxx'
        }
      ]);
    
    0 讨论(0)
  • 2021-01-07 18:39

    You can use pick and omit underscore functions to select/reject properties to test:

    const { pick, omit } = require('underscore');
    
    const obj = {
      C1: 'xxx',
      C0: 'this causes it not to match.',
    };
    
    it('tests sparse object with pick', () => {
      expect(pick(obj, 'C1')).to.eql({ C1: 'xxx' });
    });
    
    it('tests sparse object with omit', () => {
      expect(omit(obj, 'C0')).to.eql({ C1: 'xxx' });
    });
    
    0 讨论(0)
  • 2021-01-07 18:41

    Slightly updated version of #RobRaisch because for empty comparison giving error because '' not equal ""

    let expected = {
                dateOfBirth: '',
                admissionDate: '',
                dischargeDate: '',
                incidentLocation: null
            };
            Object.keys(expected).forEach(function(key) {
                expect(actual[key]).to.equal(expected[key]);
            });
    
    0 讨论(0)
提交回复
热议问题