Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add dependencies to $componentController in angular 1.5 while unit testing

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?

like image 579
oezkany Avatar asked Oct 18 '22 00:10

oezkany


1 Answers

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.

like image 128
Neo182 Avatar answered Oct 21 '22 00:10

Neo182