Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine toEqual for complex objects (mixed with functions)

Currently, I have a function that sometimes return an object with some functions inside. When using expect(...).toEqual({...}) it doesn't seem to match those complex objects. Objects having functions or the File class (from input type file), it just can't. How to overcome this?

like image 518
pocesar Avatar asked Jan 26 '13 20:01

pocesar


People also ask

Which of the following Jasmine matchers can be used for matching a regular expression?

It checks whether something is matched for a regular expression. You can use the toMatch matcher to test search patterns.

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.

How do you check if a function is called in Jasmine?

getFullName() } getFullName() { this. firstName + this. lastName } } describe('Test Person', () => { beforeEach(() => { const programmer = new Person('John', 'Gray'); spyOn(programmer, 'getFullName'); programmer. getName(); }); it('getName should call getFullName', () => { expect(programmer.

Which of the following matches function is used to test greater than condition?

The toBeGreaterThan and toBeLessThan matchers check if something is greater than or less than something else.


2 Answers

Try the Underscore _.isEqual() function:

expect(_.isEqual(obj1, obj2)).toEqual(true);

If that works, you could create a custom matcher:

this.addMatchers({
    toDeepEqual: function(expected) {
        return _.isEqual(this.actual, expected);
    };
});

You can then write specs like the following:

expect(some_obj).toDeepEqual(expected_obj);
like image 76
Vlad Magdalin Avatar answered Dec 10 '22 13:12

Vlad Magdalin


As Vlad Magdalin pointed out in the comments, making the object to a JSON string, it can be as deep as it is, and functions and File/FileList class. Of course, instead of toString() on the function, it could just be called 'Function'

function replacer(k, v) {
    if (typeof v === 'function') {
        v = v.toString();
    } else if (window['File'] && v instanceof File) {
        v = '[File]';
    } else if (window['FileList'] && v instanceof FileList) {
        v = '[FileList]';
    }
    return v;
}

beforeEach(function(){
    this.addMatchers({
        toBeJsonEqual: function(expected){
            var one = JSON.stringify(this.actual, replacer).replace(/(\\t|\\n)/g,''),
                two = JSON.stringify(expected, replacer).replace(/(\\t|\\n)/g,'');

                return one === two;
            }
    });
});

expect(obj).toBeJsonEqual(obj2);
like image 44
pocesar Avatar answered Dec 10 '22 11:12

pocesar