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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With