-->

How to test Angular 1.6 component with injected se

2019-07-25 21:42发布

问题:

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