问题单元测试控制器:日志记录控制器返回一个承诺

时间:2015-12-21 18:59:08

标签: angularjs unit-testing jasmine angularjs-controlleras

我试图测试使用controllerAs语法的控制器。我的问题是,当我尝试在控制器上测试一个函数时,我得到"预期未定义的定义。"

控制器(缩短版)

(function (angular) {
  'use strict';

  /* @ngInject */
  function PreflightCtrl($state, $window, $timeout, $stateParams, toastr, accountService, servicesService, geoService, visitService, localStorageService, Notifications, service, UTILS) {

    /* Exported Vars */
    var vm = this;

    /* Exported functions */
    vm.verifyDob = verifyDob;

    function verifyDob() {
      if (!vm.form.dob || (vm.form.dob.length !== 8 && vm.form.dob.length !== 10)){
        return;
      }
      if(vm.form.dob.length === 8){
        var lastTwoDigits = vm.form.dob.substr(vm.form.dob.length-2);
        if(lastTwoDigits === '19'){
          return;
        }
      }
      var dob = new Date(vm.form.dob);
      vm.verifyingDob = true;
      accountService.verifyDOB(dob)
        .success(function(data){
          vm.genderDisabled = false;
          vm.dobError = false;
          $timeout(function() {
            dobInput.blur();
          });
        })
        .error(function (status) {
          vm.genderDisabled = true;
          vm.dobError = true;
        })
        .finally(function () {
          vm.verifyingDob = false;
        });
    }
  }

  angular
    .module('app')
    .controller('PreflightCtrl', PreflightCtrl);

}(angular));

测试

describe('PreflightCtrl', function(){
  var PreflightCtrl, $state, $window, $timeout, $stateParams, toastr, accountService, servicesService, geoService, visitService, localStorageService, Notifications, service, UTILS, mockAccountService, mockServicesService;

  beforeEach(module('app'));

  beforeEach(inject(function($controller, _$state_, _$window_, _$timeout_, _$stateParams_, _toastr_, _accountService_, _servicesService_, _geoService_, _visitService_, _localStorageService_, _Notifications_, _UTILS_){

    //mock services used in PreflightCtrl
    mockAccountService = {
      verifyDOB: function verifyDOB(dob){
        return {
          success: function(callback){
            callback(dob);
          }
        }
      },
      isPermUser: function isPermUser(){
        return {
          success: function(callback){
            callback(true);
          }
        }
      },
      profile: {
        gender: 'male'
      }
    };

    mockServicesService = {
      isGenderAllowed: function isGenderAllowed(serviceCode, gender){
        return true;
      }
    }

    //prepare for dependency injection
    $state = _$state_;
    $window = _$window_;
    $timeout = _$timeout_;
    $stateParams = _$stateParams_;
    toastr = _toastr_;
    accountService = mockAccountService;
    servicesService = mockServicesService;
    geoService = _geoService_;
    visitService = _visitService_;
    localStorageService = _localStorageService_;
    Notifications = _Notifications_;
    service = {"id": 3, "code": "HL", "flags": {"multi_medicine": false}, "genders": ["male"], "name": "Hair Loss", "product": {"count": 3}, "visible": 1};
    UTILS = _UTILS_;

    //spy on the mocked services
    spyOn(accountService, 'verifyDOB').and.callThrough();
    spyOn(servicesService, 'isGenderAllowed').and.callThrough();

    //create the controller
    PreflightCtrl = $controller('PreflightCtrl', {
      $state: $state,
      $window: $window,
      $timeout: $timeout,
      $stateParams: $stateParams,
      toastr: toastr,
      accountService: accountService,
      servicesService: servicesService,
      geoService: geoService,
      visitService: visitService,
      localStorageService: localStorageService,
      Notifications: Notifications,
      service: service,
      UTILS: UTILS
    });

  }));

  it('should have a defined controller', function(){
    expect(PreflightCtrl).toBeDefined();
  });

  it('should have a defined function called verifyDob', function(){
    console.log(PreflightCtrl);
    expect(PreflightCtrl.verifyDob).toBeDefined();
  });

  it('should verify a DOB', function(){

    PreflightCtrl.form.dob = '01/01/1990';
    PreflightCtrl.verifyDob();
    expect(PreflightCtrl.verifyingDob).toBe(false);
  });
});

当我运行测试时,这是我得到的输出:

跑步"业力:单位" (业力)任务 PhantomJS 1.9.8(Mac OS X 0.0.0)日志:'警告:尝试不止一次加载角度。'

日志:承诺{$$ state:Object {status:2,value:Error {message:...}}} PhantomJS 1.9.8(Mac OS X 0.0.0)PreflightCtrl应该有一个名为verifyDob FAILED的定义函数     预期未定义的定义。         at /Users/tracy/Projects/LemonaidClinic/src/views/preflight/preflight.controller.spec.js:80 PhantomJS 1.9.8(Mac OS X 0.0.0)PreflightCtrl应验证DOB FAILED     TypeError:' undefined'不是一个对象(评估' PreflightCtrl.form.dob =' 01/01/1990'')         at /Users/tracy/Projects/LemonaidClinic/src/views/preflight/preflight.controller.spec.js:85 PhantomJS 1.9.8(Mac OS X 0.0.0):执行15 of 15(2失败)(0.006秒/0.204秒) 警告:任务"业力:单位"失败。使用--force继续。

因警告而中止。

第80行是这一行:expect(PreflightCtrl.verifyDob).toBeDefined();

和第85行是这样的:PreflightCtrl.form.dob =' 01/01/1990';

你可以看到第一行是控制器的日志,它返回一个promise,这意味着控制器上没有任何函数或变量需要存在。

我也不确定为什么Angular会尝试加载多次,但它似乎并没有影响任何其他测试。

我做错了什么?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

我会更喜欢这样做:

var scope = $rootScope.$new();

$controller('myController as vm', {$scope:scope, /*your dependency tree hell*/});
$rootScope.$apply();

vm = scope.vm;//This is your new controller, you can refer to it in tests.

我认为你必须嘲笑的事实说你的Controller有太多的依赖,直接和/或间接。

但是,如果您无法解决这个问题,只需创建一个名为" mocks"的文件夹,就可以更轻松地进行模拟。并删除与真实ID相同的文件并将Karma指向该文件夹。这些将覆盖实际的依赖项。缺点是,如果你需要的东西不同于你注册的模拟,你仍然需要做一次性的模拟,但它消除了在每次测试中必须设置模拟的任务。