Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Test a controller that use RouteParams

I need to test a Controller that use $routeParams to define it action. Maybe it is a test problem, or is wrong the way I wrote the controller, so now I can't write a test.

Here is my controller

angular.module('cmmApp')
.controller('UserCtrl', function ($scope, $location, $routeParams, $ionicLoading, $ionicPopup, Userservice) {

    //if a user id is set retrieve user information
    if(typeof $routeParams.id !== 'undefined'){

        var loader = $ionicLoading.show({content: "Retrieving user data"});

        var user = Userservice.get({id: $routeParams.id}).$promise;

        user.then(function(res){
            console.log(res);
            $scope.user = res.user;
            loader.hide();
        });
    }
    //else create an empty resource
    else {
        $scope.user = new Userservice;
    }
});

Basically I only want to load a resource if an id is provided is $routeParams, else create an empty resource.

And here is the test:

'use strict';

describe('Controller: UserCtrl', function () {

  // load the controller's module
  beforeEach(module('cmmApp'));

  var UserCtrl,
      scope,
      routeParams;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope, $routeParams, Userservice) {
    scope = $rootScope.$new();
    routeParams = $routeParams;
    UserCtrl = $controller('UserCtrl', {
      $scope: scope
    });

    console.log("routeParams");
    routeParams = {id: 8490394};
    console.warn(routeParams);
  }));

  it('should create an epmty user', function () {
    console.log(scope.user);
    expect(scope.user).toEqual({});

  });

});

When I run grunt test karma reply:

Controller: UserCtrl should create an epmty user FAILED
    Expected {  } to equal {  }.
    Error: Expected {  } to equal {  }.
    at null.<anonymous>    (/Users/carlopasqualicchio/Sites/CMM_Ionic/test/spec/controllers/user.js:28:24)

I'm wonering how to tell karma to change $routeParams.idbefore a test to run, and assign a different value in two different test (I need to set it to null in the first, and to a value to the other).

Any help is appreciated.

Thanks, Matt.

like image 670
teone Avatar asked Jun 09 '14 14:06

teone


1 Answers

You can pass a custom $routeParams object using the second argument of $controller (locals object), i.e. the same way you pass the $scope:

UserCtrl = $controller('UserCtrl', {
    $scope: scope,
    $routeParams: {id: '...'}
});
like image 57
gkalpak Avatar answered Oct 17 '22 14:10

gkalpak