【问题标题】:How to mock $http.post method that has been called in other service method in jasmine?如何模拟 jasmine 中其他服务方法中调用的 $http.post 方法?
【发布时间】:2017-03-14 14:48:53
【问题描述】:

我有我想测试的角度服务。在他的一种方法中,我使用了 $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() 返回承诺,所以我认为我需要考虑这一点。

【问题讨论】:

  • 你可能想编辑你的问题标题,说你需要帮助嘲笑$http.post,这似乎是主要问题

标签: javascript angularjs unit-testing mocking jasmine


【解决方案1】:

这听起来正是$httpBackend 的用途。

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

如果你确实使用$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 提交给实际的 url 并得到你的假返回值。

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

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

【讨论】:

  • 只是为了确定。在这个方法中,expect 函数做了什么? (此声明的目的是什么?)。而这个return [200, '{"progress":601}'];是什么会返回给then函数?
  • 我通过更新我的答案回答了你的问题。
【解决方案2】:

P.S 请记住 $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。服务无法向用户指示成功或失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 2011-07-02
    • 1970-01-01
    相关资源
    最近更新 更多