柴-测试对象数组中的值 [英] Chai - Testing for values in array of objects

查看:75
本文介绍了柴-测试对象数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am setting up my tests for the results to a REST endpoint that returns me an array of Mongo database objects.

[{_id: 5, title: 'Blah', owner: 'Ted', description: 'something'...},
 {_id: 70, title: 'GGG', owner: 'Ted', description: 'something'...}...]

我希望我的测试验证的是,它在return数组中包含应返回的特定标题.我使用Chai/ Chai-Things 似乎无济于事.我假设类似res.body.savedResults.should.include.something.that.equals({title: 'Blah'})这样的错误,因为记录对象除了标题外还包含其他键和值.

What I want my tests to verify is that in the return array it conatins the specific titles that should return. Nothing I do using Chai/Chai-Things seems to work. Things like res.body.savedResults.should.include.something.that.equals({title: 'Blah'}) error out I'm assuming since the record object contains other keys and values besides just title.

有没有一种方法可以使它按我的意愿去做?我只需要验证标题是否在数组中,而不必关心其他数据可能是什么(即IE _id).

Is there a way to make it do what I want? I just need to verify that the titles are in the array and don't care what the other data might be (IE _id).

谢谢

推荐答案

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

This is what I usually do within the test:

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']);

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

If you know the order of the return array you could also do this:

expect(result).to.have.deep.property('[0].title', 'expected_title_1');
expect(result).to.have.deep.property('[1].title', 'expected_title_2');

这篇关于柴-测试对象数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆