How can I change $rourParam in each test?

I'm unit testing an angular app and I'm new at it.

Inside my controller I have if statements based on $routeParams.templateID

In my Jasmine test, I try to set the $routeParam.templateID to get to the "else if" and "else" part of an if statement in my controller but in my controller, I never get to those parts of the statement.

Controller parts:

if($routeParams.templateID === undefined) {
...
else if($routeParams.templateID === "new") {
... Never get here in my code coverage
else {
... here neither

Test:

describe("TemplateController tests", function() {
    var $scope, $location, $rootScope, $window, controller, $httpBackend, $http, $routeParams;

    beforeEach(module("MyApp"));
    beforeEach(inject(function($injector, $controller) {

        $httpBackend = $injector.get('$httpBackend');
        $location = $injector.get('$location');
        $http = $injector.get('$http');
        $rootScope = $injector.get('$rootScope');
        $window = $injector.get('$window');
        $scope = $rootScope.$new();
        $window.sessionStorage.token = "xxx"
        $routeParams = $injector.get('$routeParams');

        controller = $controller("TemplateController", {
            "$scope": $scope
        });
    }));

    it("Should be able to get evaluations for course", function(){
        $routeParams.templateID = undefined;
        var evaluationTemplates = [
          {
            "ID": 1
          },
          {
            "ID": 2
          }
        ];

        $httpBackend.when('GET', 'http://localhost:1935/templates').respond(evaluationTemplates);
        $httpBackend.expectGET('http://localhost:1935/templates');


        $httpBackend.flush();
    })

    it("Should be able to get a specific evaluation", function(){
        $routeParams.templateID = "new"; // this never happenes

        expect($scope.view).toBeFalsy();
    })
});

Answers


AngularJS doesn't have any special mock for $routeParams, but since those params are just a map we don't really need a dedicated mock. What you can do is to just inject a plain old JS object into your controller, sth like this:

ctrl = $controller('MyAppCtrl', { 
            $scope: scope, 
            $routeParams : routeParams 
        }); 

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/rKS5E/5/

I found the answer here


Need Your Help

Storing Blog Comments/Upvotes - Tracking Users?

sql asp.net-mvc-3 database-design schema

I am working on a blog-type website in ASP .net MVC3. I am trying to figure out how I will deal with post upvotes/downvotes(I will have to know what users have already voted where to prevent spam v...