我正在使用Karma / Jasmine来测试给定的类。我需要测试一个数组包含一个具有给定属性的对象,即我不想指定整个对象(它相当大,如果必须的话,测试将变得不那么可维护。)
我尝试了以下内容:
expect(filters.available).toContain(jasmine.objectContaining({name:"majors"});
但这给了我错误'jasmine'没有定义,我无法找出错误的原因。
答案 0 :(得分:11)
在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'});
});
});