如何茉莉测试一个AngularJS控制器调用返回的承诺服务方法 [英] How to test with Jasmine an AngularJS controller that calls service method that returns promise

查看:114
本文介绍了如何茉莉测试一个AngularJS控制器调用返回的承诺服务方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用的茉莉测试框架AngularJS的V1.2.0-rc.3。

I am using v1.2.0-rc.3 of AngularJS with Jasmine test framework.

我想断言控制器调用服务方法。该服务方法返回一个承诺。该控制器是这样的:

I am trying to assert that a controller calls a service method. The service method returns a promise. The controller looks like this:

angular.module('test', [])
.controller('ctrl', ['$scope', 'svc', function ($scope, svc) {
  $scope.data = [];
  svc.query()
  .then(function (data) {
    $scope.data = data;
  });
}]);

欲测试数据被分配给的范围时,服务方法的延期得到解决。我创建了一个模拟的服务和单元测试是这样的:

I want to test that data is assigned to the scope when the service method's deferred is resolved. I have created a mock for the service and the unit test looks like this:

describe('ctrl', function () {
  var ctrl, scope, svc, def, data = [{name: 'test'}];
  beforeEach(module('test'));
  beforeEach(inject(function($controller, $rootScope, $q) {
    svc = {
      query: function () {
        def = $q.defer();
        return def.promise;
      }
    };
    scope = $rootScope.$new();
    controller = $controller('ctrl', {
      $scope: scope,
      svc: svc
    });
  }));
  it('should assign data to scope', function () {
    spyOn(svc, 'query').andCallThrough();
    deferred.resolve(data);
    scope.$digest();
    expect(svc.query).toHaveBeenCalled();
    expect(scope.data).toBe(data);
  });
});

我预计SVC的查询方法被调用,但显然它没有。

I expect the query method of svc to be called, but apparently it hasn't.

我跟着这个指南href=\"http://codingsmackdown.tv/blog/2012/12/28/mocking-promises-in-unit-tests/\">在单元测试嘲讽的承诺

I followed this guide to mocking promises in unit tests.

我在做什么错了?

推荐答案

看来我还是把我的间谍在错误的地方。当我把它放在beforeEach,测试通过。

It seems I was placing my spy in the wrong place. When I place it in the beforeEach, the test passes.

  beforeEach(inject(function($controller, $rootScope, $q) {
    svc = {
      query: function () {
        def = $q.defer();
        return def.promise;
      }
    };
    spyOn(svc, 'query').andCallThrough();
    scope = $rootScope.$new();
    controller = $controller('ctrl', {
      $scope: scope,
      svc: svc
    });
  }));

这篇关于如何茉莉测试一个AngularJS控制器调用返回的承诺服务方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆