如何使用注入服务测试Angular 1.6组件?

时间:2017-02-01 16:20:02

标签: angularjs unit-testing karma-jasmine angular-components angularjs-1.6

我想测试我的Angular组件,它在语法上基于John Papa's styleguide

'use strict';

 angular.module('MyModule')
    .component('MyCmpnt', MyCmpnt())
    .controller('MyCtrl', MyCtrl);

function MyCmpnt() {

    return {
        restrict: 'E',
        templateUrl: 'myPath/myTemplate.html',
        bindings: {
            foo: '=',
            bar: '<'
        },
        controller: 'MyCtrl',
        controllerAs: 'vm'
    };
}

MyCtrl.$inject = ['MyService'];

function MyCtrl (MyService) {
    // controller logic
}

正如您所见,我想注入 MyService到控制器中,间谍服务上的函数中。

我的测试代码:

'use strict';

describe('component: MyCmpnt', function () {

    var $componentController,
        MyService;

    beforeEach(module('MyModule'));

    beforeEach(module(function ($provide) {
        $provide.value('MyService', MyService);

        spyOn(MyService, 'serviceFunc').and.callThrough();
    }));

    beforeEach(inject(function (_$componentController_) {
        $componentController = _$componentController_;
    }));


    it('should initiate the component and define bindings', function () {

        var bindings = {
            foo: 'baz',
            bar: []
        };

        var ctrl = $componentController('MyCmpnt', null, bindings);

        expect(ctrl.foo).toBeDefined();
    });
});

但是,此设置让我遇到以下错误:

  

TypeError:undefined不是构造函数(评估'$ componentController('MyModule',null,bindings)')

1 个答案:

答案 0 :(得分:1)

上面的代码有$componentController('MyModule'...,没有MyModule组件。

调用MyService时,

spyOn(MyService...变量未定义。这将引发错误,阻止应用程序正确引导。

如果测试装置使用PhantomJS,这可能导致beforeEach块中的错误抑制,以便正确报告Chrome Karma启动器的错误报告。

如果问题是在定义模拟服务时未定义MyService,则可以将其定义为存根:

beforeEach(module(function ($provide) {
    $provide.value('MyService', {
      serviceFunc: jasmine.createSpy().and.callThrough()
    });
}));
相关问题