Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a jasmine matcher to compare objects on subsets of their properties

I have an object that may be extended along my behavior under test, but I want to make sure that the original properties are still there.

var example = {'foo':'bar', 'bar':'baz'}

var result = extendingPipeline(example)
// {'foo':'bar', 'bar':'baz', 'extension': Function}

expect(result).toEqual(example) //fails miserably

I'd like to have a matcher that would pass in this case, along the lines of:

expect(result).toInclude(example)

I know that I can write a custom matcher, but it seems to me that this is such a common problem that a solution should be out there already. Where should I look for it?

like image 893
iwein Avatar asked Mar 10 '13 13:03

iwein


People also ask

How do you compare objects in Jasmine?

You are trying to compare two different instances of an object which is true for regular equality ( a == b ) but not true for strict equality ( a === b). The comparator that jasmine uses is jasmine. Env. equals_() which looks for strict equality.

What is matcher in Jasmine?

Jasmine is a testing framework, hence it always aims to compare the result of the JavaScript file or function with the expected result. Matcher works similarly in Jasmine framework. Matchers are the JavaScript function that does a Boolean comparison between an actual output and an expected output.


2 Answers

Jasmine 2.0

expect(result).toEqual(jasmine.objectContaining(example))

Since this fix: https://github.com/pivotal/jasmine/commit/47884032ad255e8e15144dcd3545c3267795dee0 it even works on nested objects, you just need to wrap each object you want to match partially in jasmine.objectContaining()

Simple example:

it('can match nested partial objects', function ()
{
    var joc = jasmine.objectContaining;
    expect({ 
        a: {x: 1, y: 2}, 
        b: 'hi' 
    }).toEqual(joc({
        a: joc({ x: 1})
    }));
});
like image 113
Kamil Szot Avatar answered Oct 21 '22 19:10

Kamil Szot


I've had the same problem. I just tried this code, it works for me :

expect(Object.keys(myObject)).toContain('myKey');
like image 21
Chicna Avatar answered Oct 21 '22 19:10

Chicna