Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocha/Chai JSON comparison fails

I am using mocha and chai for testing my angular services. In a few test cases I want to compare two objects. One of it is transformed to JSON and parsed from JSON back to an object.

If I use chai to compare the tow objects, the test fails. This is my test code:

var expected = {name: 'TestObject'};
window.localStorage.setItem('test', angular.toJson(expected));

var actual = StorageService.get('test');
expect(actual).to.equal(expected);

And this is the implementation of the StorageService.get() function:

function get(name) {
    if (angular.isDefined(webStorage)) {
        var value = webStorage.getItem(name);
        if (angular.isObject(value)) {
            return null;
        }

        return angular.fromJson(value);
    }
}

The error message is the following:

AssertionError: expected { name: 'TestObject' } to equal { name: 'TestObject' }

For me the two objects seem to be the same. What is the problem here?

like image 230
Georg Leber Avatar asked Nov 01 '25 19:11

Georg Leber


2 Answers

Use deep equal

expect(actual).to.deep.equal(expected);

See reference: https://www.chaijs.com/api/bdd/#method_deep

like image 80
Brendan Tackney Avatar answered Nov 03 '25 10:11

Brendan Tackney


I have changed the test to compare the JSON representation of the two objects instead of comparing the objects directly:

var expected = angular.toJson({name: 'TestObject'});
window.localStorage.setItem('test', expected);

var actual = StorageService.get('test');        
expect(angular.toJson(actual)).to.equal(expected);

This gives the correct test result.

like image 21
Georg Leber Avatar answered Nov 03 '25 10:11

Georg Leber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!