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?
Use deep equal
expect(actual).to.deep.equal(expected);
See reference: https://www.chaijs.com/api/bdd/#method_deep
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With