Jasmine.js comparing arrays

后端 未结 4 1864
灰色年华
灰色年华 2020-12-13 05:36

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])
         


        
4条回答
  •  情深已故
    2020-12-13 05:58

    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);
    });
    

提交回复
热议问题