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

javascript - Chai test array of objects to "contain something like" an object submatch - Stack Overflow

programmeradmin1浏览0评论

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 like the following:

var expect = require('chai').expect;
var data = [ { name: 'test', value: 'bananas' } ];
expect(data).to.be.an('array').that.contains.somethig.like({name: 'test'});

Just to clarify, my intention is to get as close to the example provided as possible.

  • to chain after the .be.an('array') and
  • to provide only the partial object as a parameter (unlike chai-subset).

I really thought that expect(data).to.be.an('array').that.deep.contains({name: 'test'}); would work, but it fails on not being a partial match and I'm kinda screwed there.

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 like the following:

var expect = require('chai').expect;
var data = [ { name: 'test', value: 'bananas' } ];
expect(data).to.be.an('array').that.contains.somethig.like({name: 'test'});

Just to clarify, my intention is to get as close to the example provided as possible.

  • to chain after the .be.an('array') and
  • to provide only the partial object as a parameter (unlike chai-subset).

I really thought that expect(data).to.be.an('array').that.deep.contains({name: 'test'}); would work, but it fails on not being a partial match and I'm kinda screwed there.

Share Improve this question edited Oct 13, 2021 at 15:40 KyleMit 30k72 gold badges506 silver badges697 bronze badges asked Jun 16, 2017 at 18:19 kub1xkub1x 3,5521 gold badge39 silver badges42 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 11

Since [email protected] 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'});

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/

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

expect(data).to.be.an("array").to.containSubset([{ name: "test" }]);

A solution without third libraries or plugins:

var data = [ { name: 'test', value: 'bananas' } ];
expect(data.map(({name}) => ({name})).to.deep.include({name: 'test'});
发布评论

评论列表(0)

  1. 暂无评论