我有以下 Jasmine 单元测试:
describe('getAlertsByUserId', function () {
it('should get alerts from api/Alert/bob when the username is bob', inject(function (AlertService, $httpBackend) {
$httpBackend.when('GET', 'api/Alert/bob').respond(mockAlerts);
var alerts = AlertService.getAlertsByUserId('bob');
$httpBackend.flush();
expect(alerts).toEqual(mockAlerts);
}));
});
mockAlerts 定义如下:
[{
date: new Date(2013, 5, 25),
description: '',
alertType: 'type1',
productDescription: 'product',
pack: 12,
size: 16,
unitOfMeasure: 'OZ',
category: 'cat1',
stage: 'C',
status: 'I'
}]
当我在 Karma 中执行测试时,我得到“Expected [ {date:...etc }] to equal [ {date:...etc }]。我已经验证了两个对象是相同的(属性/值)。我尝试删除 Date 对象,但无济于事。有人吗?
最佳答案
toEqual
将检查引用是否相等,即警报对象与 mockAlerts 是同一对象。您要检查的是对象相等性。有几种方法可以做到这一点。
首先你可以将你的对象转换成json
expect(JSON.stringify(alerts)).toEqual(JSON.stringify(mockAlerts));
这可能在大多数情况下都有效,但它确实取决于序列化程序以完全相同的方式处理对象。
另一种方法是使用 angular.equals。
expect(angular.equals(alerts, mockAlerts)).toBeTruthy();
这可能不太好读,但应该能很好地工作。
关于javascript - AngularJS 服务单元测试在 toEqual 上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17433447/