3

I'm using Karma, Mocha, Sinon and Chai for my Angular unit tests and I'm trying to figure out how to mock a redirect I'm doing in my controller with $location.

My controller does the following redirect:

$location.path('home');

I want to try and mock that redirect using spies, this is what I'm currently doing:

describe('Auth Controller', function() {
  var controller;
  var $location;

  beforeEach(function() {
    bard.appModule('app.auth');
    bard.inject('$controller', '$rootScope', '$location');
  });

  beforeEach(function() {
    $location = {
      path: sinon.spy().returned('Fake location')
    };
    controller = $controller('authCtrl', { $scope: $rootScope, $location: $location });
  });

  it('should take you to the metrics page on successful login', function() {
    expect($location.path).to.have.been.calledWith("Fake location");
  });

});

I'm getting the following error:

TypeError: false is not a spy or a call to a spy!

I'm not sure how to go about mocking this correctly or if I'm even going about this in the right way.

Any help for unit testing experts are appreciated. Thanks in advance!

realph
  • 4,481
  • 13
  • 49
  • 104
  • Why you need mock $location? Normally I don't mock it, i just use expect like that expect(location.path()).toBe('/myPage'); – Rafael Zeffa Nov 23 '15 at 19:42
  • Is there any particular reason you do it this way? I thought the idea was to mock the $location service. – realph Nov 23 '15 at 19:45
  • There is no particular reason, for me it's the simplest way to test a redirection behavior – Rafael Zeffa Nov 23 '15 at 19:58
  • @RafaelZeffa So I'm trying this: `expect($location.path()).to.equal('login');` but I'm getting this error: `TypeError: Cannot read property 'path' of undefined`. – realph Nov 23 '15 at 21:05

1 Answers1

3

You can use Spies for testing location.path like this (see f.e. here: Spy on a service method call using jasmine Spies):

var location, objectUnderTest;

beforeEach(inject(function($location){
  location = $location;
}));
function YourCtrlMaker() {
    objectUnderTest = $controller('YourCtrl', {
        $scope: $scope,
        $location: location,
        $routeParams: $routeParams,
    })
}
it('should test location.path', function(){
  spyOn(location, 'path');
  YourCtrlMaker();
  $scope.$root.$digest();
  expect(location.path).toHaveBeenCalledWith('example.com/objects/');
});
Community
  • 1
  • 1
M.Void
  • 2,764
  • 2
  • 29
  • 44