我有要测试的角度服务。在他的一种方法中,我正在使用$ http的角度服务。我只是想模拟该函数(更具体地说是模拟$ http.post函数),该函数将返回我想要的任何东西并将该模拟注入到我的服务测试中。

我试图找到解决方案,但发现$ httpBackend,但是我不确定这是否可以帮助我。

MyService看起来像这样:

angular.module('app').service('MyService' , function (dependencies) {
    let service = this;
    service.methodToTest = function () {
        $http.post('url').then(function () {
            // Do something
        });
    }
}



我想测试methodToTest并注入$ http.post()的模拟


P.S请记住$ http.post()返回promise,所以我认为我需要考虑这一点。

最佳答案

这听起来完全像$httpBackend的用途。

如果在测试中注入$http.post,您也可以通过执行$http.post = jasmine.createSpy();之类的方法仅模拟$http,但我不知道。

如果您确实使用$httpBackend,也许这个例子可以帮助您,在您的茉莉花测试中做这样的事情

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.posturl并执行此功能。它应该就像提交给实际methodToTesturl一样,并得到假的返回值。

返回值指示成功的http状态代码(200),并返回您在第二个参数中输入的任何内容作为响应的data属性(此处为response.data == '{"progress":601}')。这将在then函数中。见How do I mock $http in AngularJS service Jasmine test?

expect函数仅是一个示例(不需要),以向您显示可以根据需要在其中放置expect子句。

关于javascript - 如何模拟 Jasmine 中其他服务方法中已调用的$ http.post方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42789183/

10-12 12:52
查看更多