我正在将结果的测试设置到REST端点,该端点返回一组Mongo数据库对象。
[{_id: 5, title: 'Blah', owner: 'Ted', description: 'something'...},
{_id: 70, title: 'GGG', owner: 'Ted', description: 'something'...}...]
我希望我的测试验证的是,在返回数组中,它包含应该返回的特定标题。我使用Chai / Chai-Things做的事情似乎都没有用。像res.body.savedResults.should.include.something.that.equals({title: 'Blah'})
这样的事情错误我正在假设,因为记录对象除了标题之外还包含其他键和值。
有没有办法让它做我想要的?我只需要验证标题是否在数组中,而不关心其他数据可能是什么(IE _id)。
谢谢
这是我在测试中通常做的事情:
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']);
如果你知道返回数组的顺序,你也可以这样做:
expect(result).to.have.deep.property('[0].title', 'expected_title_1');
expect(result).to.have.deep.property('[1].title', 'expected_title_2');
如上所述here以下代码现在与[email protected]和chai-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'});
另一种解决方案是使用函数扩展数组对象,以测试数组中是否存在具有与期望值匹配的所需属性的对象,如下所示
/**
* @return {boolean}
*/
Array.prototype.HasObjectWithPropertyValue = function (key, value) {
for (var i = 0; i < this.length; i++) {
if (this[i][key] === value) return true;
}
return false;
};
(我把它放在我的主要test.js文件中,以便所有其他嵌套测试都可以使用该函数)
然后你可以在你的测试中使用它
var result = query_result;
// in my case (using superagent request) here goes
// var result = res.body;
result.HasObjectWithPropertyValue('property', someValue).should.equal(true);