AngularJS服务单元测试在toEqual上失败

Bja*_*ram 2 javascript jasmine angularjs karma-runner

我有以下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);
    }));
});
Run Code Online (Sandbox Code Playgroud)

mockAlerts定义如下:

[{
        date: new Date(2013, 5, 25),
        description: '',
        alertType: 'type1',
        productDescription: 'product',
        pack: 12,
        size: 16,
        unitOfMeasure: 'OZ',
        category: 'cat1',
        stage: 'C',
        status: 'I'
}]
Run Code Online (Sandbox Code Playgroud)

当我在Karma中执行测试时,我得到"Expected [{date:... etc}]等于[{date:... etc}].我已经验证了两个对象是相同的(属性/值).我尝试删除Date对象,但无济于事.任何人?

Der*_*ins 8

toEqual将检查引用相等性,即alert对象是作为mockAlerts的THE SAME对象.您要检查的是对象相等.有几种方法可以做到这一点.

首先,您可以将对象转换为json

expect(JSON.stringify(alerts)).toEqual(JSON.stringify(mockAlerts));
Run Code Online (Sandbox Code Playgroud)

这可能大部分时间都可以工作,但它确实依赖于序列化器以完全相同的方式处理对象.

另一种方法是使用angular.equals.

expect(angular.equals(alerts, mockAlerts)).toBeTruthy();
Run Code Online (Sandbox Code Playgroud)

这可能不会读取,但应该很好地工作.