Chris Jager Chris Jager - 15 days ago 7
AngularJS Question

Angular 1.5 component unit testing with webpack

I'm trying to test a component with controller, with some bindings:

class AppSpecificController {
constructor() {
this.text = this.initialText ? this.initialText : 'No initial text has been specified.';
}
}

export const AppSpecificComponent = {
bindings: {
'initialText': '<bindInitialText'
},
templateUrl: '/app/components/app-specific/app-specific.html',
controller: AppSpecificController,
controllerAs: 'appSpecific'
};

export default AppSpecificComponent;


In my unit test file I don't want to load the complete application, just the things I need. So I figured to mock a module or just create a new one named something with mock, add the component to that module, and load that module:

import {AppSpecificComponent} from './app-specific.component';

describe('AppSpecificComponent', () => {
let controller;
let scope;
let $componentController;

beforeEach(() => {
angular.module('mock-module', [])
.component('appSpecific', AppSpecificComponent);

// this fails
module('mock-module');

inject((_$componentController_, $rootScope) => {
scope = $rootScope.$new();
$componentController = _$componentController_;
});

controller = $componentController('appSpecific', {$scope: scope}, {initialText: 'Some text'});
});

it('should test something', () => {
expect(true).toBeTruthy();
});
});


Creating the module mock-module is fine, but loading it fails, and obviously injecting stuff in the not-so-much-loaded-module fails, as well as creating a controller on which I can start testing. It would be nice to be able to test the components individually, separate from the application in which it runs.

Just using the new operator for the class AppSpecificController doesn't work since then the bindings you receive from the component are not there:

// fails, no bindings available in controller
controller = new AppSpecificController();

Answer

I found the answer somewhere else on StackOverflow, not sure where anymore. The answer however I was looking for:

angular.mock.module($provide => {
  $provide.controller('SomeController', () => { ... });
  $provide.constant('someConstant', 'some constant');
});