AngularJS:返回 $http 承诺的测试工厂 [英] AngularJS : Testing factory that returns $http promises
问题描述
尝试测试返回 $http
GET 请求和 then
处理程序的 Angular 服务,但我无法测试该逻辑是否实际在then
函数.这是服务代码的基本截断版本:
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();
});
});
我觉得我已经尝试了几乎所有方法来测试 then
调用中的逻辑,所以如果有人能提供建议,我将不胜感激.
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
来伪造响应 - 在测试
then
回调中,将响应设置为回调外部可用的变量,以便您可以在expect
调用中对其进行测试 - 确保
expect
调用在任何回调之外,以便它始终运行并显示任何失败.
- 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);
});
正如在 http://plnkr.co/edit/9zON7ALKnrKpcOVrBupQ?p=preview 中所见
这篇关于AngularJS:返回 $http 承诺的测试工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!