Reputation: 211
I want to add dependencies to my Controller in a component:
Here is my component:
angular
.module('app')
.component('myComponent', {
template: '<div>some content</div>',
controller: ["$routeParams", function ($routeParams) {
var ctrl = this;
ctrl.myId = $routeParams.id;
});
Now I just want to test this as follow:
describe("spec for myComponent", function () {
var $componentController;
var $routeParams;
beforeEach(module('app'));
beforeEach(inject(function (_$componentController_, _$routeParams_) {
$componentController = _$componentController_;
$routeParams = _$routeParams_;
$routeParams = {
myId: 42
}
}));
it('should init', function () {
var ctrl = $componentController('myComponent', $routeParams, null);
expect(ctrl.myId).toBe(42);
});
});
But unfortunately ctrl.myId is undefined because $routeParams are not correctly injected. Why?
Upvotes: 4
Views: 3476
Reputation: 1136
You seem to be re-defining $routeParams
here:
$routeParams = _$routeParams_;
$routeParams = {
myId: 42
}
Doing the following should solve your problem (also note that you expect id
to be and attribute of $routeParams
, not myId
):
$routeParams = _$routeParams_;
$routeParams.id = 42;
Upvotes: 1
Reputation: 612
I had very similar situation as yours, googled for a while but found almost nothing, but at last I solved the problem myself : Here is the solution for your case:
describe("spec for myComponent", function () {
var $componentController;
var mockRouteParams = {id : 1};
beforeEach(module('app'));
beforeEach(inject(function (_$componentController_) {
$componentController = _$componentController_;
}));
it('should init', function () {
var ctrl = $componentController('myComponent', {$routeParams:mockRouteParams}, null);
expect(ctrl.myId).toBe(1);
});
});
Also check Mocking $routeParams in a test in order to change its attributes dynamically regarding mocking of $routeParams.
Upvotes: 2