javascript 茉莉花:检查数组是否包含具有给定属性的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24341746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jasmine: check that an array contains an element with given properties
提问by dabs
I'm using Karma/Jasmine to test a given class. I need to test that an array contains an object with a given property, i.e. I don't want to specify the whole object (it is rather large and the test would become less maintainable if I had to).
我正在使用 Karma/Jasmine 来测试给定的课程。我需要测试一个数组是否包含一个具有给定属性的对象,即我不想指定整个对象(它相当大,如果必须的话,测试将变得不太可维护)。
I've tried the following:
我尝试了以下方法:
expect(filters.available).toContain(jasmine.objectContaining({name:"majors"});
but this gave me the error 'jasmine' is not defined, and I haven't been able to figure out the cause of that error.
但这给了我错误“茉莉花”未定义,我无法找出该错误的原因。
采纳答案by Leonidas Kapsokalivas
One way of doing it in jasmine 2.0
is to use a custom matcher. I also used lodash
to iterate over the array and inthe objects inside each array item:
一种方法jasmine 2.0
是使用自定义匹配器。我还用于lodash
遍历数组和每个数组项内的对象:
'use strict';
var _ = require('lodash');
var customMatcher = {
toContain : function(util, customEqualityTesters) {
return {
compare : function(actual, expected){
if (expected === undefined) {
expected = '';
}
var result = {};
_.map(actual, function(item){
_.map(item, function(subItem, key){
result.pass = util.equals(subItem,
expected[key], customEqualityTesters);
});
});
if(result.pass){
result.message = 'Expected '+ actual + 'to contain '+ expected;
}
else{
result.message = 'Expected '+ actual + 'to contain '+ expected+' but it was not found';
}
return result;
}
};
}
};
describe('Contains object test', function(){
beforeEach(function(){
jasmine.addMatchers(customMatcher);
});
it('should contain object', function(){
var filters = {
available: [
{'name':'my Name','id':12,'type':'car owner'},
{'name':'my Name2','id':13,'type':'car owner2'},
{'name':'my Name4','id':14,'type':'car owner3'},
{'name':'my Name4','id':15,'type':'car owner5'}
]
};
expect(filters.available).toContain({name : 'my Name2'});
});
});