出于特定目的,我必须编写一个返回 $timeout
promise 的工厂方法,该 promise 在其内部返回一个 $http.get
promise 。
我想测试对我的工厂方法的调用是否会使用正确的模拟 URL (mocked-get-path
) 调用 $http.get
。
这是我的工厂代码:
(function() {
'use strict';
angular.module('MyApp', []);
angular.module('MyApp')
.constant("ROUTES", {
get: "real-get-path"
});
angular.module('MyApp')
.factory('MyFactory', ['$http', '$timeout', 'ROUTES', MyFactory]);
function MyFactory($http, $timeout, ROUTES) {
return {
myGet: function(id) {
var random = Math.random() * 1000;
return $timeout(function () {
return $http.get(ROUTES.get, {
params: { id: id }
})
.then(function() {
return response.data;
});
}, random);
}
};
}
})();
以及我的测试规范:
describe('simple factory test', function() {
var $http, $timeout, scope, MyFactory;
var ROUTES = {
get: 'mocked-get-path'
};
beforeEach(module('MyApp', function ($provide) {
$provide.constant('ROUTES', ROUTES);
}));
beforeEach(module('MyApp'));
beforeEach(inject(function(_$rootScope_, _$http_, _$timeout_, _MyFactory_) {
scope = _$rootScope_.$new();
$http = _$http_;
$timeout = _$timeout_;
MyFactory = _MyFactory_;
}));
it('should use ROUTES.get on method myGet', function(done) {
spyOn(Math, "random").and.returnValue(0.01);
MyFactory.myGet('elem1')
.then(function(res) {
expect($http.get).toHaveBeenCalledWith(ROUTES.get);
done();
});
$timeout.flush();
});
});
你可以看到我尝试在then
内为$http.get
编写一个expect
,但是没有成功.
我从 Jasmine 收到此错误:
Error: Unexpected request: GET mocked-get-path?id=elem1
我做了一个Plunker:https://plnkr.co/edit/Ia6Q6GvKZOkNU2B8GrO1
我做错了什么?
最佳答案
测试 $http
时,您将需要使用 $httpBackend.when
就您而言:
it('should use ROUTES.get on method myGet', function(done) {
spyOn(Math, "random").and.returnValue(0.01);
spyOn($http, "get").and.callThrough();
MyFactory.myGet('elem1')
.then(function(res) {
expect($http.get).toHaveBeenCalledWith(ROUTES.get, {params: {id: 'elem1'}});
done();
});
$httpBackend
.when('GET', "mocked-get-path?id=elem1")
.respond(200, { foo: 'bar' });
$timeout.flush(100);
$timeout.verifyNoPendingTasks();
$httpBackend.flush();
});
这将导致 $httpBackend
成功完成您的请求,从而允许您的 .then
执行预期。
我希望这有帮助!祝你有美好的一天!
关于javascript - 如何测试返回 $timeout promise 且内部包含 $http.get 的 AngularJS 工厂方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40155513/