本文介绍了AngularJS:测试工厂,返回HTTP $承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想测试的角度服务,返回 $ HTTP
GET请求,并在然后
的处理程序,但我中号无法测试,逻辑实际工作的然后
函数中。这里是服务code的基础上,截断版本:
Trying to test an angular service that returns an $http
GET request and the then
handler, but I'm not able to test that the logic actually works inside of the then
function. Here is a basic, truncated version of the service code:
angular.module('app').factory('User', function ($http) {
var User = {};
User.get = function(id) {
return $http.get('/api/users/' + id).then(function (response) {
var user = response.data;
user.customProperty = true;
return user;
});
};
return User;
});
这是测试:
beforeEach(module('app'));
beforeEach(inject(function(_User_, _$q_, _$httpBackend_, _$rootScope_) {
$q = _$q_;
User = _User_;
$httpBackend = _$httpBackend_;
$scope = _$rootScope_.$new();
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingRequest();
$httpBackend.verifyNoOutstandingExpectation();
});
describe('User factory', function () {
it('gets a user and updates customProperty', function () {
$httpBackend.expectGET('/api/users/123').respond({ id: 123 });
User.get(123).then(function (user) {
expect(user.customProperty).toBe(true); // this never runs
});
$httpBackend.flush();
});
});
我觉得我已经试过pretty所有事情,以测试在然后
调用逻辑,因此,如果有人能提供建议,我将不胜AP preciate吧。
I feel like I've tried pretty much everything to test the logic in the then
call, so if someone can offer suggestions I would greatly appreciate it.
编辑:我的问题也是由于非标准注射做法,所以答案如下工作之外的那
my problem was also due to nonstandard injection practices, so the answer below worked outside of that.
推荐答案
需要有几件事情要改变
- 使用以虚假的响应
whenGET
而不是expectGET
的 - 在测试
然后
回调,设置可在回调外,所以你可以在期望$ C测试它的响应变量$ C>呼叫
- 确保该
期望
调用任何回调之外,因此它始终运行并显示任何故障。
- Use
whenGET
instead ofexpectGET
in order to fake a response - In the test
then
callback, set the response to a variable available outside the callback so you can test it in anexpect
call - Make sure the
expect
call is outside any callbacks, so it always runs and shows any failures.
全部放在一起:
it('gets a user and updates customProperty', function () {
$httpBackend.whenGET('/api/users/123').respond({ id: 123 });
User.get(123).then(function(response) {
user = response;
})
$httpBackend.flush();
expect(user.customProperty).toBe(true);
});
由于可以在
这篇关于AngularJS:测试工厂,返回HTTP $承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!