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?
It checks whether something is matched for a regular expression. You can use the toMatch matcher to test search patterns.
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.
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.
The toBeGreaterThan and toBeLessThan matchers check if something is greater than or less than something else.
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);
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);
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