How to test Angular 1.6 component with injected service?

情到浓时终转凉″ 提交于 2020-01-05 08:10:27

问题


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)')


回答1:


The code above has $componentController('MyModule'..., and there is no MyModule component.

MyService variable is undefined when spyOn(MyService... is called. This will throw an error prevent the application from being bootstrapped correctly.

If testing rig uses PhantomJS, this may lead to error suppression in beforeEach blocks, for correct error reporting Chrome Karma launcher is recommended.

If the problem is that MyService is undefined at the point where mocked service is defined, it can be defined in-place as a stub:

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


来源:https://stackoverflow.com/questions/41984613/how-to-test-angular-1-6-component-with-injected-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!