最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mocha Chai: Deep include an array of objects, but only have part of expected object - Stack Overflow

programmeradmin5浏览0评论

I'm using the assert syntax of chai for this.

I know that if I want to check an array of objects for a specific object, I can do this:

assert.deepInclude(
  [
    { name: 'foo', id: 1 },
    { name: 'bar', id: 2 }
  ], 
  { name: 'foo', id: 1 }
)

Which should pass.

But what if I only have 1 property in the object that I'm checking for...? Like this:

assert.deepInclude(
  [
    { name: 'foo', id: 1 },
    { name: 'bar', id: 2 }
  ], 
  { name: 'foo' }
)

I still want this to pass, but it's telling me it's failing because that exact object does not exist.

I'm using the assert syntax of chai for this.

I know that if I want to check an array of objects for a specific object, I can do this:

assert.deepInclude(
  [
    { name: 'foo', id: 1 },
    { name: 'bar', id: 2 }
  ], 
  { name: 'foo', id: 1 }
)

Which should pass.

But what if I only have 1 property in the object that I'm checking for...? Like this:

assert.deepInclude(
  [
    { name: 'foo', id: 1 },
    { name: 'bar', id: 2 }
  ], 
  { name: 'foo' }
)

I still want this to pass, but it's telling me it's failing because that exact object does not exist.

Share Improve this question asked Jun 24, 2020 at 3:54 Alec MatherAlec Mather 85811 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Using chai-subset this can be done pretty easily:

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

it('should contain subset', () => {
    const actual = [
      { name: 'foo', id: 1 },
      { name: 'bar', id: 2 },
    ];

    expect(actual).to.containSubset([{ name: 'foo' }]);
});

Afaik there's no way to do this with chai alone, but you could write your own function:

function containsPartialObj(arr, obj) {
  return arr.some(entry => {
    const keys = Object.keys(obj);
    return keys.every(key => obj[key] === entry[key]);
  });
}

it('should contain subset', () => {
     const actual = [
        { name: 'foo', id: 1 },
        { name: 'bar', id: 2 },
     ];
    
     expect(containsPartialObj(actual, { name: 'foo' })).to.be.true;
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论