如何模拟在jasmine中以其他服务方法调用的$ http.post方法?

时间:2017-03-14 14:48:53

标签: javascript angularjs unit-testing mocking jasmine

我有想要测试的角色服务。在他的一个方法中,我使用$ 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()
  • 的模拟

请注意$ http.post()返回promise,所以我认为我需要考虑一下。

2 个答案:

答案 0 :(得分:1)

这听起来恰恰是$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并执行此功能。它应该像提交给实际methodToTest的{​​{1}}一样,并获得假的返回值。

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

then函数只是一个示例(不需要),表明如果需要,可以在其中放置expect子句。

答案 1 :(得分:1)

  

请注意$http.post()返回承诺,所以我认为我需要考虑这一点。

服务需要返回该承诺:

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

当函数省略return语句时,它返回值undefined。服务无法向用户指示成功或失败。

相关问题