Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
10
rated 0 times [  13] [ 3]  / answers: 1 / hits: 21281  / 10 Years ago, sat, june 21, 2014, 12:00:00

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).



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.


More From » arrays

 Answers
101

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:



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

[#70488] Thursday, June 19, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nikhilh

Total Points: 224
Total Questions: 89
Total Answers: 99

Location: Bahrain
Member since Fri, Sep 16, 2022
2 Years ago
;