【问题标题】:Karma tests failing with the good values?业力测试以良好的价值失败?
【发布时间】:2015-11-18 09:00:04
【问题描述】:

我开始使用 karma 进行一些单元测试,但我不知道为什么我的第一个测试没有通过。

这是一个控制器文件:

angular.module('balrogApp.requests', [
  /* Dependancies */
])
  // Routes configuration
  .config(['$routeProvider', function($routeProvider) {
    /* $routeProvider configuration */
  }])
  .controller('requestsController', function(Requests, Users, Projects, RequestsComments, CostEstimations,
                                             Regions, growl, $route, $rootScope, $scope, $location) {
    this.requestTypesList = [
  {name: "New", trigram: "NEW"},
  {name: "Enhancement", trigram: "ENH"}
];
     this.requestPrioritiesList = [
  {name: "Low", trigram: "LOW"},
  {name: "Medium", trigram: "MED"},
  {name: "High", trigram: "HIG"}
];

/* ... */

});

这是测试文件:

describe('Requests controller', function() {
  beforeEach(module('balrogApp.requests'));

  var ctrl;
  var scope;

  var requestTypesList = [
    {name: "New", trigram: "NEW"},
    {name: "Enhancement", trigram: "ENH"}
  ];

  var requestPrioritiesList = [
    {name: "Low", trigram: "LOW"},
    {name: "Medium", trigram: "MED"},
    {name: "High", trigram: "HIG"}
  ];

  beforeEach(inject(function($rootScope, $controller) {
    scope = $rootScope.$new();
    ctrl = $controller('requestsController', { $scope: scope });
  }));

  afterEach(function() {
    scope.$destroy();
  });

  it('should have proper requestTypesList value', function(){
    expect(ctrl.requestTypesList).toBe(requestTypesList);
  });

  it('should have proper requestPrioritiesList value', function(){
    expect(ctrl.requestPrioritiesList).toBe(requestPrioritiesList);
  });
});

但这是测试的结果:

Chrome 43.0.2357 (Windows 7 0.0.0) 请求控制器应该有 正确的 requestTypesList 值失败

预期

[ Object({ name: 'New', trigram: 'NEW' }), Object({ name: '增强',三元组:'ENH' }) ]

成为

[ Object({ name: 'New', trigram: 'NEW' }), Object({ name: '增强',三元组:'ENH' }) ].

在对象。 (C:/Users/aazor102115/Desktop/Dev/Balrog/tests/requests.js:28:35)

Chrome 43.0.2357 (Windows 7 0.0.0) 请求控制器应该有 正确的 requestPrioritiesList 值失败

预期 [ Object({ name: 'Low', trigram: 'LOW' }), Object({ name: '中', trigram: 'MED' }), Object({ name: 'High', trigram: 'HIG' }) ]

成为

[ Object({ name: 'Low', trigram: 'LOW' }), Object({ name: 'Medium', trigram: 'MED' }), Object({ name: 'High', trigram: 'HIG' }) ].

在对象。 (C:/Users/aazor102115/Desktop/Dev/Balrog/tests/requests.js:32:40) Chrome 43.0.2357 (Windows 7 0.0.0):执行 2 of 2 (2 FAILED) 错误 (0.12 秒 / 0.105 秒)

因此,即使日志中的值相同,测试也会失败。为什么会这样以及如何解决?

【问题讨论】:

    标签: javascript angularjs unit-testing karma-jasmine


    【解决方案1】:

    将您的toBe 断言更改为toEqual,它们在内存中不是同一个对象。

    【讨论】:

    • toBe() 类似于===toEqual() 类似于==
    • toEqual() 比较对象键和属性以查看它们是否应该被视为相等。 {} == {} 仍然是假的。
    猜你喜欢
    • 2020-06-10
    • 2016-10-02
    • 2016-01-09
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2015-11-28
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多