如何模拟在jasmine中以其他服务方法调用的$ http.post方法? [英] How to mock $http.post method that has been called in other service method in jasmine?
问题描述
我有想要测试的角色服务。在他的一个方法中,我使用$ http的角度服务。我只是想模拟那个函数(更具体的模拟$ http.post函数),它会返回我想要的东西并将这个模拟注入我的服务测试。
I have and angular service that I want to test. In one of his methods I am using $http of angular service. I am simply want to mock that function (to be more specific mock $http.post function) that would return whatever I want and inject this mock to my service test.
我试图找到解决方案,我发现$ httpBackend但我不确定这可以帮助我。
I am tried to find solution and I found $httpBackend but I am not sure that this could help me.
MyService看起来像这样:
MyService looks like that:
angular.module('app').service('MyService' , function (dependencies) {
let service = this;
service.methodToTest = function () {
$http.post('url').then(function () {
// Do something
});
}
}
- 我想测试methodToTest并注入$的模拟http.post()
PS请记住$ http.post()返回promise,所以我认为我需要考虑。
P.S please remember that $http.post() returns promise so I think that I need to consider in that.
推荐答案
这听起来就像 $ httpBackend
适用于。
this sounds like exactly what $httpBackend
is for.
您也可以通过执行类似的操作来模拟
如果你在测试中注入 $ http.post
$ http.post = jasmine.createSpy(); $ http
,但我不知道。
You might also be able to mock only $http.post
by doing something like $http.post = jasmine.createSpy();
if you inject $http
in your test, but I don't know.
如果您确实使用 $ httpBackend
,也许这个例子可以帮助您在茉莉花测试中做这样的事情
If you do use $httpBackend
, perhaps this example helps you, in your jasmine test do something like this
beforeEach(inject(function(_$httpBackend_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$httpBackend = _$httpBackend_;
$httpBackend.whenRoute('POST', 'url')
.respond(function(method, url, data, headers, params) {
expect(somevariable).toContain(params.something);
return [200, '{"progress":601}'];
});
}));
$ httpBackend
将拦截所有 $ http.post
到 url
并执行此功能。它应该像 methodToTest
一样提交给实际的 url
并获得假的返回值。
the $httpBackend
will intercept all $http.post
's to url
and execute this function. It should be just like the methodToTest
submitted to the actual url
and got your fake return value.
返回值表示成功的http状态代码(200),并返回您在第二个参数中放置的任何内容,作为 data
属性响应(此处 response.data =='{progress:601}'
)。这将在然后
函数中。请参阅如何在AngularJS服务Jasmine测试中模拟$ http ?
The return value indicates a success http status code (200) and returns whatever you put in the second argument as the data
property of the response (here response.data == '{"progress":601}'
). Which will be in the then
function. See How do I mock $http in AngularJS service Jasmine test?
期望
函数只有一个例子(不需要),向您展示你可以在那里放一个 expect
子句。
The expect
function there is just an example (not needed), to show you that you can put an expect
clause there if you want.
这篇关于如何模拟在jasmine中以其他服务方法调用的$ http.post方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!