AngularJS: unit testing ui-router state changes

964 Views Asked by At

I am fairly new to unit testing in angular so bear with me please!

I have a $stateProvidor setup for my app and would like to test that the routing part does work correctly.

Say I have this sort of config:

angular.module("app.routing.config", []).config(function($stateProvider, $urlRouterProvider) {
  $stateProvider.state("home", {
    url: "/",
    templateUrl: "app/modules/home/page/home_page.html",
    controller: "HomePageController",
    resolve: {
      setPageTitle: function($rootScope) {
        return $rootScope.pageTitle = "Home";
      }
    }
  }).state("somethingelse", {
    url: "/",
    templateUrl: "app/modules/home/page/somethingelse.html",
    controller: "SomeThingElseController",
    resolve: {
      setPageTitle: function($rootScope) {
        return $rootScope.pageTitle = "Some Thing Else";
      }
    }
  });
  return $urlRouterProvider.otherwise('/');
});

I came across this blog post on how to set up unit testing for a ui-router config, so I Have tried to adopt the same approach, here is my test I am trying out:

'use strict';
describe('UI-Router State Change Tests', function() {
  var $location, $rootScope, $scope, $state, $templateCache;
  beforeEach(module('app'));
  beforeEach(inject(function(_$rootScope_, _$state_, _$templateCache_, _$location_) {
    $rootScope = _$rootScope_;
    $state = _$state_;
    $templateCache = _$templateCache_;
    $location = _$location_;
  }));
  describe('State Change: home', function() {
    beforeEach(function() {
      $templateCache.put(null, 'app/modules/home/page/home_page.html');
    });
    it('should go to the home state', function() {
      $location.url('home');
      $rootScope.$digest();
      expect($state.href('home')).toEqual('#/');
      expect($rootScope.pageTitle).toEqual('Home');
    });
  });
});

When running the test I am getting this error in the output:

Error: Unexpected request: GET app/modules/home/page/home_page.html

Clearly I am doing something wrong here, so any help or pointers would be much appreciated.

I did come across $httpBackend, is this something I should also be using here, so telling my test to expect a request to the html page my state change test is making?

1

There are 1 best solutions below

0
On

This is almost certainly down to a partial html view (home_page.html) being loaded asynchronously during app / test runtime.

In order to handle this, you can preprocess your html partials into Javascript strings, which can then be loaded synchronously via your tests.

Have a look at karma-ng-html2js-preprocessor which should solve your problem.