gpt4 book ai didi

javascript - 在 Angular js 中测试加载器

转载 作者:行者123 更新时间:2023-12-02 17:25:24 27 4
gpt4 key购买 nike

这是使用加载器对 $resource 进行的测试

describe('Service: MultiCalculationsLoader', function(){

beforeEach(module('clientApp'));

var MultiCalculationLoader,
mockBackend,
calculation;

beforeEach(inject(function (_$httpBackend_, Calculation, _MultiCalculationLoader_) {
MultiCalculationLoader = _MultiCalculationLoader_;
mockBackend = _$httpBackend_;
calculation = Calculation;
}));

it('should load a list of calculation from a user', function(){
mockBackend.expectGET('/api/user/600/calculation').respond([{id:5}]);

var calculations;
var mockStateParams = {
userId: 600
};
var promise = new MultiCalculationLoader(mockStateParams);

promise.then(function(res){
calculations = res
});

expect(calculations).toBeUndefined();

mockBackend.flush();

expect(calculations).toEqual([{id:5}]);
});

});

当我运行测试时,出现以下错误:

Expected [ { id : 5 } ] to equal [ { id : 5 } ].
Error: Expected [ { id : 5 } ] to equal [ { id : 5 } ].
at null.<anonymous>

我不明白。这两个数组对我来说是相同的。有人有想法吗?

更新这是实现:

 .factory('Calculation', function ($resource) {
return $resource('/api/user/:userId/calculation/:calcId', {'calcId': '@calcId'});
})
.factory('MultiCalculationLoader', function (Calculation, $q) {
return function ($stateParams) {
var delay = $q.defer();
Calculation.query( {userId: $stateParams.userId},function (calcs) {
delay.resolve(calcs);
}, function () {
delay.reject('Unable to fetch calculations');
});
return delay.promise;
};
})

最佳答案

您期望的 url 与实际 url 不同。我想你需要这样的东西:

it('should load a list of calculation from a user', function(){
//remove the 's' from 'calculations'
mockBackend.expectGET('/api/user/600/calculation').respond([{id:5}]);

var calculations;
var promise = MultiCalculationLoader({userId:600}); //userId = 600
promise.then(function(res){
calculations = res
});

expect(calculations).toBeUndefined();

mockBackend.flush();

expect(calculations).toEqual([{id:5}]);
});

还有一个问题,Angular 会自动向响应添加 2 个属性:

enter image description here

http://plnkr.co/edit/gIHolGd85SLswzv5VZ1E?p=preview

这与以下问题相同:AngularJS + Jasmine: Comparing objects

当 Angular 将响应转换为资源对象时,这确实是 Angular $resource 的问题。为了验证来自 $resource 的响应,您可以尝试 angular.equals

expect(angular.equals(calculations,[{id:5},{id:6}])).toBe(true);

http://plnkr.co/edit/PrZhk2hkvER2XTBIW7yv?p=preview

您还可以编写自定义匹配器:

beforeEach(function() {
jasmine.addMatchers({
toEqualData: function() {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});

并使用它:

expect(calculations).toEqualData([{id:5},{id:6}]);

http://plnkr.co/edit/vNfRmc6R1G69kg0DyjZf?p=preview

关于javascript - 在 Angular js 中测试加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23550772/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com