Angular.js单元测试控制器与其他模块的依赖关系

时间:2017-08-14 09:39:07

标签: angularjs unit-testing karma-jasmine

背景:

我有一个angular.js控制器' GetResultController'与一些外部依赖:

angular.module('data-service',[]).service('DataService', DataService);

angular.module('GetResultModule', ['datatables', 'data-service']);
angular.module('GetResultModule')
       .controller('GetResultController',
       ['$q','DTColumnBuilder','DataService', GetResultController]);

function GetResultController($q, DTColumnBuilder, DataService) {
    let self = this;
    self.getResult = function getResult() {
        return 'positive';
    }
}

问题:

VER-1:

describe('testGetResultController', () =>{
    beforeEach(angular.mock.module('datatable');
    //do i need to create the mock module for 'data-service', and how to do next? 
    }
)

VER-2:

describe('testGetResultController', () => {
    beforeEach(angular.module('datatable',[]);
    beforeEach(angular.module('common-service',[]);
    let c;
    beforeEach(angular.mock.inject(function(_$controller_) {
      c = _$controller_('GetResultController'); // is it correct to get back the controller?
    }
    it('test', ()=> {
      expect(c).toBeDefined(); // why c is undefined?
    });
})

因为我想起草一个单元测试来验证' GetResultController'。如何初始化依赖项,模拟对象以测试' getResult'方法。我们有经验来处理这种情况。

非常感谢

0 个答案:

没有答案