Reputation: 4217
I'm following the documentation for testing Angular 1.5 components.
I'm getting an error where $componentController is undefined. I'm sure it is something simple but I just can't see what is wrong here.
here is my test component.
class MyComponent {
constructor() {
this.counter = 0;
}
$onChanges() {}
$onDestroy() {}
addToCounter() {
this.counter += 1;
}
}
MyComponent.$inject = [];
angular.module( 'my.component', [] )
.component( 'MyComponent', {
controller: MyComponent,
bindings: {},
template: `
<div>Hello World</div>
`,
} );
Here is the test
describe( 'module: my.component', function() {
var $componentController;
beforeEach( module( 'my.component' ) );
beforeEach( inject( function( _$componentController_ ) {
$componentController = _$componentController_;
} ) );
it( 'should default counter to 0', function() {
var bindings = {};
console.log( '$componentController', $componentController );
var ctrl = $componentController( 'MyComponent', null, bindings );
expect( ctrl.counter )
.toEqual( 0 );
} );
} );
Here what Jasmine is outputting
LOG: '$componentController', undefined
...
TypeError: undefined is not a constructor (evaluating '$componentController( 'MyComponent', null, bindings )') in ...
Upvotes: 2
Views: 1213
Reputation: 1206
First, you need to change your component name from "MyComponent" to "myComponent", a component name needs to start with a lower case letter.
I changed the test a bit by fetching the controller in the inject:
let controller;
beforeEach(() => {
angular.mock.module( 'my.component' );
inject(($componentController) => {
controller = $componentController("myComponent");
});
});
After doing so I ran these 3 tests:
describe("Just some test", () => {
it("should fetch controller", () => {
expect(controller).toBeDefined();
});
it("counter should be 0", () => {
expect(controller.counter).toBe(0);
});
it("should increase counter value to 1", () => {
controller.addToCounter();
expect(controller.counter).toBe(1);
});
});
And they all passed.
Upvotes: 2