Pindakaas
Pindakaas

Reputation: 4439

how to construct unit test for controller with $state?

Trying to write a unit test for my controller:

 app.controller('StartGameCtrl', function ($scope, $timeout,$state) {
      $scope.startGame = function () {
        $scope.snap = false;
        $scope.dealCards();
        debugger;
        $state.go('cpu');
      }
    });

I wrote this jasmine unit test:

describe('snap tests', function() {
  beforeEach(module('snapApp'));
  var scope, createController, state;

  beforeEach(inject(function ($rootScope, $controller,$state) {
    scope = $rootScope.$new();
    createController = function () {
      return $controller('StartGameCtrl', {
        '$scope':scope,
        '$state':state
      });
    };
  }));


  it('startGame should call dealcards', function () {
    var controller = createController();
    spyOn(scope, 'dealCards');
    scope.startGame();
    //expect(scope.dealCards).toHaveBeenCalled();
  });

});

when I run my karma test I get an error:

TypeError: 'undefined' is not an object (evaluating '$state.go')
at startgamectrl.js:9

Upvotes: 0

Views: 1391

Answers (1)

Phil
Phil

Reputation: 164752

You've assigned the $state local to be state (an undefined var in your spec) instead of the injected $state service.

Rather than do that though, I'd just create a spy for $state. For example...

beforeEach(inject(function ($rootScope, $controller) {
    scope = $rootScope.$new();
    state = jasmine.createSpyObj('$state', ['go']);
    createController = function () {
        return $controller('StartGameCtrl', {
            '$scope':scope,
            '$state':state
        });
    };
}));

Then you can test that it's called

expect(state.go).toHaveBeenCalledWith('cpu');

Upvotes: 1

Related Questions