如何单元测试AngularJS $ promise.then

时间:2014-03-05 02:20:52

标签: angularjs unit-testing coffeescript promise

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

这是在coffeescript中。如何对此进行单元测试:

厂:

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

服务:

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

控制:

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

我试图通过以下方式对此进行测试:

beforeEach:

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);

1 个答案:

答案 0 :(得分:0)

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

服务:

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

控制:

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);