Ste77
Ste77

Reputation: 676

Javascript tests - How to compare two objects in Jasmine

Very new to Javascript TDD, and working with Jasmine at the moment.

I have a problem comparing two objects.

The function I am testing is being assigned an object as passed as a define ( I'm using require ) -

define(
['jquery',
 'src/frameManager'],
function($,FrameManager){

    return {

        // OBJECTS
        frameManager    : FrameManager,

    ....

    }

And here's my test:

define(['init', '../../../src/frameManager'], function (init, frameManager) {

...

it("Init to contain property frameManager with type frameManager", function() {
        console.log(init.frameManager)
        console.log(frameManager)
        expect(init.frameManager).toEqual(jasmine.any(frameManager));
    });

 ....

 });

The two console logs show me exactly the same objects, but I am getting this error:

 TypeError: Expecting a function in instanceof check, but got #<Object>

I have also tried the above without the jasmine.any:

expect(init.frameManager).toEqual(frameManager);

But still no joy. I get the following error in this case:

Error: Expected Object({ iframe: ({ context: HTMLNode, selector: '#preview-frame' }), frameContents: false, parent: false, templateBody: false, parsedTemplate: false, services: Object({ url: false, type: false, data: false, dataType: false, callback: false, call: Function, set: Function, ajaxService: Function, isEmpty: Function }), init: Function, setOptions: Function, parseIframe: Function, registerEvents: Function, getParsedTemplate: Function, populateIframe: Function }) to equal Object({ iframe: ({ context: HTMLNode, selector: '#preview-frame' }), frameContents: false, parent: false, templateBody: false, parsedTemplate: false, services: Object({ url: false, type: false, data: false, dataType: false, callback: false, call: Function, set: Function, ajaxService: Function, isEmpty: Function }), init: Function, setOptions: Function, parseIframe: Function, registerEvents: Function, getParsedTemplate: Function, populateIframe: Function }).

As you can see, both objects are exactly the same... Does anyone have any suggestions?

Thanks.

Upvotes: 0

Views: 1440

Answers (1)

Nick Rassadin
Nick Rassadin

Reputation: 900

Easiest way to compare two objects deeply is to use next condition

JSON.stringify(obj1) == JSON.stringify(obj2);

So just modify your code

expect(JSON.stringify(init.frameManager)).toEqual(JSON.stringify(frameManager));

If you use object comparison multiple times in your test, consider to create custom matcher

Upvotes: 1

Related Questions