如何根据约翰爸爸风格指南在angularjs中写测试

时间:2016-09-06 09:32:29

标签: angularjs testing controller

我是刚刚在angularjs.中编写测试的。我有一个控制器,我根据john papa样式指南编写。我需要在我的测试用例中访问控制器中的那些方法。我该怎么办?我正在使用jasmine。我的示例代码是:

(function(){
  angular.module('myapp')
  .controller('AlertsController', AlertsController);
AlertsController.$inject = ['$scope', 'StorageFactory']
function AlertsController($scope, StorageFactory) {
  var vm=this;
  vm.createAlert=createAlert();
  function createAlert(){
    //function code
    }  
})

我的测试如下:

 'use strict';
 describe('Controller: AlertsController', function() {
var AlertsController, scope, StorageFactory;

beforeEach(module('myapp'));
beforeEach(inject(function(_$controller_, _StorageFactory_,      _$rootScope_) {
    scope = _$rootScope_.$new();
    AlertsController = _$controller_;
    StorageFactory = _StorageFactory_;
}));

var createController = function() {
    AlertsController('AlertsController', {
        '$scope': scope,
        'StorageFactory': StorageFactory
    });

};
 it('should create an alert', function() {
    spyOn(StorageFactory, 'isLoggedIn').and.callFake(function() {
        return true;
    });
    createController();
    expect(AlertsController).toBeDefined();
    AlertsController.createAlert();  
});
});

我收到以下错误:

TypeError: undefined is not a constructor (evaluating 'AlertsController.createAlert()') in /Users/Ramya/Documents/panitr_mobile/test/spec/controllers/AlertsCtrlSpec.js (line 57)
    at /Users/Ramya/Documents/panitr_mobile/test/spec/controllers/AlertsCtrlSpec.js:57:37
PhantomJS 2.0.0 (Mac OS X 0.0.0): Executed 2 of 2 (1 FAILED) (0 secs / 0.242 secPhantomJS 2.0.0 (Mac OS X 0.0.0): Executed 2 of 2 (1 FAILED) (0.054 secs / 0.242 secs)

1 个答案:

答案 0 :(得分:0)

对于Jhon Papa样式,您不需要使用scope创建$new。 只需在创建控制器而不是{}时传递$scope

将控制器初始化放在beforeEach;

    beforeEach(inject(function(_$controller_, _StorageFactory_,      _$rootScope_) {
            AlertsController = _$controller_;
            StorageFactory = _StorageFactory_;
            AlertsController('AlertsController', {} });
        }));

it("creatAlert should be defined",function(){

     expect(AlertsController.creatAlert ).toBe(true);
})