Himanshu
Himanshu

Reputation: 2361

Testing $state.go giving error in Angular JS spec

I am having below Controller in Angular JS

describe('Controller: homeCtrl', function () {
  beforeEach(module('incident'));
  var homeCtrl, $state;

  beforeEach(inject(function ($controller, _$state_) {
      $state = _$state_;
      homeCtrl = $controller('homeCtrl', {$state: $state});
  }));

  it('to be defined', function () {
    expect( homeCtrl).toBeDefined();
  });

  it('to be defined state', inject(function ($state) {
      $state.expectTransitionTo('incidents');
  }));
});

While writing spec for $state.go like below, it is giving error as per attached image:

describe('Controller: homeCtrl', function () {
  beforeEach(module('incident'));
  var homeCtrl, $state;

  beforeEach(inject(function ($controller, _$state_) {
      $state = _$state_;
      homeCtrl = $controller('homeCtrl', {$state: $state});
  }));

  it('to be defined state', inject(function ($state) {
      $state.expectTransitionTo('incidents');
  }));

});

enter image description here

Any suggestion will be helpful or any sample code which shows how can i test this $state.go.

Upvotes: 1

Views: 1880

Answers (2)

ngLover
ngLover

Reputation: 4588

You need to spy on state to make transition between states.here is the code

describe('Controller: homeCtrl', function () {
  beforeEach(module('incident'));
  var homeCtrl, $state;

  beforeEach(inject(function ($controller, _$state_) {
      $state = _$state_;
       spyOn('$state','go'); spyOn($state, 'go');
       // or
       spyOn($state, 'go').andCallFake(function(state, params) {
        // This replaces the 'go' functionality for the duration of your test
       });
      homeCtrl = $controller('homeCtrl', {$state: $state});
  }));

  it('to be defined state', inject(function ($state) {
      $state.expectTransitionTo('incidents');
  }));

});

Upvotes: 4

Dan
Dan

Reputation: 10548

expectTransitionTo is not a function that ships with ui-router innately. I assume you saw it from this gist, in which case, you need to use that gist and also set up the stateMock module.

Upvotes: 0

Related Questions