Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jasmine: check that an array contains an element with given properties

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.

like image 721
dabs Avatar asked Jun 21 '14 12:06

dabs


1 Answers

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'});
    });
});
like image 145
Leonidas Kapsokalivas Avatar answered Sep 21 '22 13:09

Leonidas Kapsokalivas