AngularJS + Jasmine:比较对象

sha*_*lim 43 javascript tdd unit-testing jasmine angularjs

我刚刚开始为我的AngularJS应用程序编写测试,我在Jasmine中这样做.

以下是相关的代码段

ClientController:

'use strict';

adminConsoleApp.controller('ClientController',
    function ClientController($scope, Client) {

        //Get list of clients
        $scope.clients = Client.query(function () {
            //preselect first client in array
            $scope.selected.client = $scope.clients[0];
        });

        //necessary for data-binding so that it is accessible in child scopes.
        $scope.selected = {};

        //Current page
        $scope.currentPage = 'start.html';

        //For Client nav bar
        $scope.clientNavItems = [
            {destination: 'features.html', title: 'Features'},
        ];

        //Set current page
        $scope.setCurrent = function (title, destination) {
            if (destination !== '') {
                $scope.currentPage = destination;
            }

        };

        //Return path to current page
        $scope.getCurrent = function () {
            return 'partials/clients/' + $scope.currentPage;
        };

        //For nav bar highlighting of active page
        $scope.isActive = function (destination) {
            return $scope.currentPage === destination ? true : false;
        };

        //Reset current page on client change
        $scope.clientChange = function () {
            $scope.currentPage = 'start.html';
        };
    });
Run Code Online (Sandbox Code Playgroud)

ClientControllerSpec:

'use strict';

var RESPONSE = [
    {
        "id": 10,
        "name": "Client Plus",
        "ref": "client-plus"
    },
    {
        "id": 13,
        "name": "Client Minus",
        "ref": "client-minus"
    },
    {
        "id": 23805,
        "name": "Shaun QA",
        "ref": "saqa"
    }
];

describe('ClientController', function() {

    var scope;

    beforeEach(inject(function($controller, $httpBackend, $rootScope) {
        scope = $rootScope;
        $httpBackend.whenGET('http://localhost:3001/clients').respond(RESPONSE);
        $controller('ClientController', {$scope: scope});
        $httpBackend.flush();
    }));

    it('should preselect first client in array', function() {
        //this fails.
        expect(scope.selected.client).toEqual(RESPONSE[0]);
    });

    it('should set current page to start.html', function() {
        expect(scope.currentPage).toEqual('start.html');
    });
});
Run Code Online (Sandbox Code Playgroud)

测试失败:

Chrome 25.0 (Mac) ClientController should preselect first client in array FAILED
    Expected { id : 10, name : 'Client Plus', ref : 'client-plus' } to equal { id : 10, name : 'Client Plus', ref : 'client-plus' }.
    Error: Expected { id : 10, name : 'Client Plus', ref : 'client-plus' } to equal { id : 10, name : 'Client Plus', ref : 'client-plus' }.
        at null.<anonymous> (/Users/shaun/sandbox/zong-admin-console-app/test/unit/controllers/ClientControllerSpec.js:43:39) 
Run Code Online (Sandbox Code Playgroud)

有没有人对为什么会发生这种情况有任何想法?

另外..因为我刚开始编写AngularJS测试,所有关于我是否设置我的测试错误或是否可以改进的评论都将受到欢迎.

更新:

包括ClientService:

'use strict';

AdminConsoleApp.services.factory('Client', function ($resource) {
    //API is set up such that if clientId is passed in, will retrieve client by clientId, else retrieve all.
    return $resource('http://localhost:port/clients/:clientId', {port: ':3001', clientId: '@clientId'}, {

    });
});
Run Code Online (Sandbox Code Playgroud)

此外,我通过比较ID来解决问题:

it('should preselect first client in array', function () {
    expect(scope.selected.client.id).toEqual(RESPONSE[0].id);
});
Run Code Online (Sandbox Code Playgroud)

Umu*_*acı 66

toEqual进行深刻的平等比较.这意味着当对象的值的所有属性相等时,对象被认为是相等的.

正如您所说,您正在使用资源,它为数组中的对象添加了几个属性.

所以这{id:12}变成了{id:12, $then: function, $resolved: true}不相等的.如果您只是测试是否正确设置了值,则ID检查应该没问题.


The*_*per 56

简短回答:

现有答案都建议您对对象进行字符串化,或者创建自定义匹配器/比较函数.但是,有一种更简单的方法:angular.equals()在Jasmine expect调用中使用,而不是使用Jasmine的内置toEqual匹配器.

angular.equals()将忽略Angular添加到对象中的其他属性toEqual,但是$promise对于其中一个对象将无法进行比较.


更长的解释:

我在AngularJS应用程序中遇到了同样的问题.我们设置一下场景:

在我的测试中,我创建了一个本地对象和一个本地数组,并期望它们作为对两个GET请求的响应.之后,我将GET的结果与原始对象和数组进行了比较.我使用四种不同的方法测试了这一点,只有一种方法得到了适当的结

这是foobar-controller-spec.js的一部分:

var myFooObject = {id: 1, name: "Steve"};
var myBarsArray = [{id: 1, color: "blue"}, {id: 2, color: "green"}, {id: 3, color: "red"}];

...

beforeEach(function () {
    httpBackend.expectGET('/foos/1').respond(myFooObject);
    httpBackend.expectGET('/bars').respond(myBarsArray);

    httpBackend.flush();
});

it('should put foo on the scope', function () {
    expect(scope.foo).toEqual(myFooObject);
    //Fails with the error: "Expected { id : 1, name : 'Steve', $promise : { then : Function, catch : Function, finally : Function }, $resolved : true } to equal { id : 1, name : 'Steve' }."
    //Notice that the first object has extra properties...

    expect(scope.foo.toString()).toEqual(myFooObject.toString());
    //Passes, but invalid (see below)

    expect(JSON.stringify(scope.foo)).toEqual(JSON.stringify(myFooObject));
    //Fails with the error: "Expected '{"id":1,"name":"Steve","$promise":{},"$resolved":true}' to equal '{"id":1,"name":"Steve"}'."

    expect(angular.equals(scope.foo, myFooObject)).toBe(true);
    //Works as expected
});

it('should put bars on the scope', function () {
    expect(scope.bars).toEqual(myBarsArray);
    //Fails with the error: "Expected [ { id : 1, color : 'blue' }, { id : 2, color : 'green' }, { id : 3, color : 'red' } ] to equal [ { id : 1, color : 'blue' }, { id : 2, color : 'green' }, { id : 3, color : 'red' } ]."
    //Notice, however, that both arrays seem identical, which was the OP's problem as well.

    expect(scope.bars.toString()).toEqual(myBarsArray.toString());
    //Passes, but invalid (see below)

    expect(JSON.stringify(scope.bars)).toEqual(JSON.stringify(myBarsArray));
    //Works as expected

    expect(angular.equals(scope.bars, myBarsArray)).toBe(true);
    //Works as expected
});
Run Code Online (Sandbox Code Playgroud)

作为参考,这是console.log使用的输出JSON.stringify().toString():

LOG: '***** myFooObject *****'
LOG: 'Stringified:{"id":1,"name":"Steve"}'
LOG: 'ToStringed:[object Object]'

LOG: '***** scope.foo *****'
LOG: 'Stringified:{"id":1,"name":"Steve","$promise":{},"$resolved":true}'
LOG: 'ToStringed:[object Object]'



LOG: '***** myBarsArray *****'
LOG: 'Stringified:[{"id":1,"color":"blue"},{"id":2,"color":"green"},{"id":3,"color":"red"}]'
LOG: 'ToStringed:[object Object],[object Object],[object Object]'

LOG: '***** scope.bars *****'
LOG: 'Stringified:[{"id":1,"color":"blue"},{"id":2,"color":"green"},{"id":3,"color":"red"}]'
LOG: 'ToStringed:[object Object],[object Object],[object Object]'
Run Code Online (Sandbox Code Playgroud)

注意stringified对象如何具有额外的属性,以及如何toString产生无效数据,这将产生误报.

从上面看,这里是不同方法的总结:

  1. expect(scope.foobar).toEqual(foobar):这两种方式都失败了.比较对象时,toString显示Angular已添加了额外的属性.比较数组时,内容看起来相同,但这种方法仍然声称它们是不同的.
  2. expect(scope.foo.toString()).toEqual(myFooObject.toString()):这通过两种方式.但是,这是误报,因为对象没有被完全翻译.这使得唯一的断言是两个参数具有相同数量的对象.
  3. expect(JSON.stringify(scope.foo)).toEqual(JSON.stringify(myFooObject)) :此方法在比较数组时给出正确的响应,但对象比较与原始比较具有类似的错误.
  4. expect(angular.equals(scope.foo, myFooObject)).toBe(true):这是做出断言的正确方法.通过让Angular进行比较,它知道忽略在后端添加的任何属性,并给出正确的结果.

如果对任何人都很重要,我正在使用AngularJS 1.2.14和Karma 0.10.10,并在PhantomJS 1.9.7上进行测试.


Adr*_*ian 14

长话短说:添加angular.equals为茉莉花匹配器.

beforeEach(function(){
  this.addMatchers({
    toEqualData: function(expected) {
      return angular.equals(this.actual, expected);
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

那么,你可以按如下方式使用它:

it('should preselect first client in array', function() {
    //this passes:
    expect(scope.selected.client).toEqualData(RESPONSE[0]);

    //this fails:
    expect(scope.selected.client).toEqual(RESPONSE[0]);
});
Run Code Online (Sandbox Code Playgroud)


Pip*_*tus 6

我只是遇到了类似的问题,并根据许多方法实现了如下自定义匹配器:

beforeEach(function() {
  this.addMatchers({
    toBeSimilarTo: function(expected) {
      function buildObject(object) {
        var built = {};
        for (var name in object) {
          if (object.hasOwnProperty(name)) {
            built[name] = object[name];
          }
        }
        return built;
      }

      var actualObject = buildObject(this.actual);
      var expectedObject = buildObject(expected);
      var notText = this.isNot ? " not" : "";

      this.message = function () {
        return "Expected " + actualObject + notText + " to be similar to " + expectedObject;
      }

      return jasmine.getEnv().equals_(actualObject, expectedObject);

    }
  });
});
Run Code Online (Sandbox Code Playgroud)

然后用这种方式:

it("gets the right data", function() {
  expect(scope.jobs[0]).toBeSimilarTo(myJob);
});
Run Code Online (Sandbox Code Playgroud)

当然,它是一个非常简单的匹配器,不支持很多情况,但我不需要比这更复杂的东西.您可以将匹配器包装在配置文件中.

检查此答案以获得类似的实现.