Is there a way in jasmine.js to check if two arrays are equal, for example:
arr = [1, 2, 3]
expect(arr).toBe([1, 2, 3])
expect(arr).toEqual([1, 2, 3])
Neither seems to work.
Is there a way in jasmine.js to check if two arrays are equal, for example:
arr = [1, 2, 3]
expect(arr).toBe([1, 2, 3])
expect(arr).toEqual([1, 2, 3])
Neither seems to work.
Just did the test and it works with toEqual
please find my test:
describe('toEqual', function() {
it('passes if arrays are equal', function() {
var arr = [1, 2, 3];
expect(arr).toEqual([1, 2, 3]);
});
});
Just for information:
toBe() versus toEqual(): toEqual() checks equivalence. toBe(), on the other hand, makes sure that they're the exact same object.
You can compare an array like the below mentioned if the array has some values
it('should check if the array are equal', function() {
var mockArr = [1, 2, 3];
expect(mockArr ).toEqual([1, 2, 3]);
});
But if the array that is returned from some function has more than 1 elements and all are zero then verify by using
expect(mockArray[0]).toBe(0);
just for the record you can always compare using JSON.stringify
const arr = [1,2,3];
expect(JSON.stringify(arr)).toBe(JSON.stringify([1,2,3]));
expect(JSON.stringify(arr)).toEqual(JSON.stringify([1,2,3]));
It's all meter of taste, this will also work for complex literal objects
I had a similar issue where one of the arrays was modified. I was using it for $httpBackend
, and the returned object from that was actually a $promise
object containing the array (not an Array
object).
You can create a jasmine matcher to match the array by creating a toBeArray
function:
beforeEach(function() {
'use strict';
this.addMatchers({
toBeArray: function(array) {
this.message = function() {
return "Expected " + angular.mock.dump(this.actual) + " to be array " + angular.mock.dump(array) + ".";
};
var arraysAreSame = function(x, y) {
var arraysAreSame = true;
for(var i; i < x.length; i++)
if(x[i] !== y[i])
arraysAreSame = false;
return arraysAreSame;
};
return arraysAreSame(this.actual, array);
}
});
});
And then just use it in your tests like the other jasmine matchers:
it('should compare arrays properly', function() {
var array1, array2;
/* . . . */
expect(array1[0]).toBe(array2[0]);
expect(array1).toBeArray(array2);
});