Chai test array of objects to “contain something like” an object submatch

前端 未结 3 390
我在风中等你
我在风中等你 2021-01-21 05:15

Ok. I\'ve tried to read other questions here but still didn\'t find a straightforward answer.

How can I assert a partial object match in an array using chai? Something

相关标签:
3条回答
  • 2021-01-21 05:52

    ES6+

    Clean, functional and without dependencies, simply use a map to filter the key you want to check

    something like:

    const data = [ { name: 'test', value: 'bananas' } ];
    expect(data.map(e=>e.name)).to.include("test");
    

    and if you want to test multiple keys:

    expect(data.map(e=>({name:e.name}))).to.include({name:"test"});
    

    https://www.chaijs.com/api/bdd/

    0 讨论(0)
  • 2021-01-21 05:56

    Not sure why you dismissed chai-subset as this seems to work:

    expect(data).to.be.an("array").to.containSubset([{ name: "test" }]);
    
    0 讨论(0)
  • 2021-01-21 06:02

    Since chai-like@0.2.14 the following approch will work:

    var chai = require('chai'),
        expect = chai.expect;
    
    chai.use(require('chai-like'));
    chai.use(require('chai-things')); // Don't swap these two
    
    expect(data).to.be.an('array').that.contains.something.like({name: 'test'});
    
    0 讨论(0)
提交回复
热议问题