1

I want to test my Angular component which is syntactically based on 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
}

As you can see I want to inject MyService into the controller and spy in a function on that very service.

My test code:

'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();
    });
});

However, this setup lets me run into the following error:

TypeError: undefined is not a constructor (evaluating '$componentController('MyModule', null, bindings)')

4

1 回答 1

1

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

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

如果测试台使用 PhantomJS,这可能会导致beforeEach块中的错误抑制,为了正确报告错误,建议使用 Chrome Karma 启动器。

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

beforeEach(module(function ($provide) {
    $provide.value('MyService', {
      serviceFunc: jasmine.createSpy().and.callThrough()
    });
}));
于 2017-02-02T10:50:53.973 回答