Chai - 测试对象数组中的值

Jar*_*ach 19 arrays mocha.js chai

我正在将结果的测试设置到REST端点,该端点返回一组Mongo数据库对象.

[{_id: 5, title: 'Blah', owner: 'Ted', description: 'something'...},
 {_id: 70, title: 'GGG', owner: 'Ted', description: 'something'...}...]
Run Code Online (Sandbox Code Playgroud)

我希望我的测试验证的是,在返回数组中,它包含应该返回的特定标题.我没有用Chai/Chai-Things做什么似乎都有用.事情是这样res.body.savedResults.should.include.something.that.equals({title: 'Blah'})的错误了,我假设,因为记录对象包含其他键和值除了刚才称号.

有没有办法让它做我想要的?我只需要验证标题是否在数组中,而不关心其他数据可能是什么(IE _id).

谢谢

use*_*572 21

这是我在测试中通常做的事情.

var result = query_result;

var members = [];
result.forEach(function(e){
    members.push(e.title);
});

expect(members).to.have.members(['expected_title_1','expected_title_2']);
Run Code Online (Sandbox Code Playgroud)

如果你知道返回数组的顺序,你也可以这样做:

expect(result).to.have.deep.property('[0].title', 'expected_title_1');
expect(result).to.have.deep.property('[1].title', 'expected_title_2');
Run Code Online (Sandbox Code Playgroud)

  • 我想提一下,虽然您的答案是正确的,但最好结合使用 `.map()` 而不是 `.forEach()` 与 `push()` 。Map 比 forEach [1] 更快并且更具可读性。:) [1] https://codeburst.io/javascript-map-vs-foreach-f38111822c0f (2认同)

kub*_*b1x 19

如下所述,下面的代码现在使用chai-like@0.2.14chai-things.我只是喜欢这种方法的自然可读性.

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({title: 'Blah'});
Run Code Online (Sandbox Code Playgroud)


Seb*_*rin 9

ES6+

干净、实用且无依赖关系,只需使用映射来过滤您要检查的密钥

就像是:

const data = [{_id: 5, title: 'Blah', owner: 'Ted', description: 'something'},{_id: 70, title: 'GGG', owner: 'Ted', description: 'something'}];


expect(data.map(e=>({title:e.title}))).to.include({title:"Blah"});
Run Code Online (Sandbox Code Playgroud)

如果您只检查一个键,甚至更短:

expect(data.map(e=>(e.title))).to.include("Blah");
Run Code Online (Sandbox Code Playgroud)

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


Gui*_*oli 5

现在最好的方法可能是使用deep.members财产

这会检查无序完全相等。(不完全平等变化membersincludes

IE

expect([ {a:1} ]).to.have.deep.members([ {a:1} ]); // passes
expect([ {a:1} ]).to.have.members([ {a:1} ]); // fails
Run Code Online (Sandbox Code Playgroud)

这是一篇关于测试数组和对象 的好文章https://medium.com/building-ibotta/testing-arrays-and-objects-with-chai-js-4b372310fe6d

免责声明:这不仅是为了测试title属性,而是为了测试整个对象数组