【问题标题】:Mocking the Service in Controller according to responce type根据响应类型在控制器中模拟服务
【发布时间】:2016-04-27 08:45:51
【问题描述】:

我有一个控制器如下,它依赖于customerService,它将基于来自服务器的listParam 返回搜索result

  self.result = [];
  self.listParam= {};

  self.search= function () {
            self.result.length = 0;
            self.findingPromise = customerService.find(self.listParam);
            self.findingPromise
                .then(function (response) {
                    self.result = response.data.Result;
                }, function (response) {
                    var r = response;
                    ngNotify.set('Some problems occurred!',
                        {
                            type: 'error',
                            position: 'top',
                            sticky: true
                        });
                });
        };

我想使用 Jasmine 进行 单元测试。我读过Unit Testing for AngularJS 文章。但我不明白在这种情况下我应该如何使用 mocking (搜索)。如您所见,我可能已经根据服务后端解析了响应。

【问题讨论】:

    标签: angularjs unit-testing mocking jasmine


    【解决方案1】:

    您可以使用间谍来模拟您的服务,也许类似的东西会起作用

    spyOn(customerService, "find").and.callFake(function() {
          return {
            then:function(callback) {
                var yourReturnObject = {};
                return callback(yourReturnObject);
            }
          };
        });
    

    此外,您可以使用承诺来使您的服务正常工作或失败。

    deferred = $q.defer();
    
    spyOn(customerService, 'find').andReturn(deferred.promise);
    
    // here your asserts
    
    
    // In case that you want to make your service fail
    deferred.reject({ ... });
    
    // In case that you want to make your service work
    deferred.resolve({ ... });
    

    【讨论】:

    • 您能否提供更多关于它是如何工作的信息?我不明白这两种类型的响应是如何被管理和伪造的。
    • 你想测试什么?来自服务器的正确响应和来自服务器的失败响应?
    • 不,我现在不想测试服务。我想测试控制器操作。如果成功从服务获得响应,它将设置 html 页面的结果,如果没有,则发送错误通知。但我不知道步骤。
    • @Elnaz,请看我的回答
    猜你喜欢
    • 1970-01-01
    • 2017-03-08
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 2013-04-16
    相关资源
    最近更新 更多