【问题标题】:How to unit test AngularJS $promise.then如何对 AngularJS $promise.then 进行单元测试
【发布时间】:2014-04-06 21:20:15
【问题描述】:

我有一个使用 Angular 资源进行 API 调用的工厂。然后我创建了一个名为 getAllResources 的函数,并使用工厂来查询我的所有数据。然后在我的控制器中,我使用该服务和 $promise.then 来获取我的数据并将其存储在一个变量中。

这是在咖啡脚本中。如何对此进行单元测试:

工厂:

resource "/perm/api/account/:uid/svcs",
      uid: "@uid"
    ,
      query:
        cache: true
        isArray: true
        method: "GET"

服务:

getAllResources: (uid) ->
      factory.query(uid: uid)

Ctrl:

model.getAllResources(scope.accountID).$promise.then ((response) ->
      scope.allResources = response
      resPromise.resolve()
    ), (error) ->
      log.debug error
      state.go "pageunavailable"

我正在尝试通过以下方式对此进行测试:

在每个之前:

var def, model, service;
service = $injector.get("Service");
    model = {
    getAllResources: function() {
      def = q.defer();
      return def.promise;
    }
  };


  controller("Ctrl", {
      $scope: scope, 
      model: model
    }, service);

它():

fakeProfSvcsData = [{id:0,name:"zeon"},{id:1,name:"leo"}];
spyOn(model, "getAllResources").andCallThrough();
def.resolve(fakeProfSvcsData);
scope.$digest()

expect(scope.allResources).toEqual(fakeProfSvcsData);

【问题讨论】:

    标签: angularjs unit-testing coffeescript promise


    【解决方案1】:

    我通过修改以下代码修复了它:

    服务:

    getAllResources: (uid) ->
          factory.query(uid: uid).$promise
    

    Ctrl:

    model.getAllResources(scope.accountID).then ((response) ->
          scope.allResources = response
          resPromise.resolve()
        ), (error) ->
          log.debug error
          state.go "pageunavailable"
    

    它():

    fakeProfSvcsData = [{id:0,name:"zeon"},{id:1,name:"leo"}];
    spyOn(model, "getAllResources").andReturn(def.resolve(mockProfSvcsData));
    def.resolve(fakeProfSvcsData);
    scope.$digest()
    
    expect(scope.allResources).toEqual(fakeProfSvcsData);
    

    【讨论】:

      猜你喜欢
      • 2014-09-21
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 2019-11-02
      相关资源
      最近更新 更多