Unit Testing AngularJS directive with templateUrl

70,462

Solution 1

What I ended up doing was getting the template cache and putting the view in there. I don't have control over not using ngMock, it turns out:

beforeEach(inject(function(_$rootScope_, _$compile_, $templateCache) {
    $scope = _$rootScope_;
    $compile = _$compile_;
    $templateCache.put('path/to/template.html', '<div>Here goes the template</div>');
}));

Solution 2

You're correct that it's related to ngMock. The ngMock module is automatically loaded for every Angular test, and it initializes the mock $httpBackend to handle any use of the $http service, which includes template fetching. The template system tries to load the template through $http and it becomes an "unexpected request" to the mock.

What you need a way to pre-load the templates into the $templateCache so that they're already available when Angular asks for them, without using $http.

The Preferred Solution: Karma

If you're using Karma to run your tests (and you should be), you can configure it to load the templates for you with the ng-html2js preprocessor. Ng-html2js reads the HTML files you specify and converts them into an Angular module that pre-loads the $templateCache.

Step 1: Enable and configure the preprocessor in your karma.conf.js

// karma.conf.js

preprocessors: {
    "path/to/templates/**/*.html": ["ng-html2js"]
},

ngHtml2JsPreprocessor: {
    // If your build process changes the path to your templates,
    // use stripPrefix and prependPrefix to adjust it.
    stripPrefix: "source/path/to/templates/.*/",
    prependPrefix: "web/path/to/templates/",

    // the name of the Angular module to create
    moduleName: "my.templates"
},

If you are using Yeoman to scaffold your app this config will work

plugins: [ 
  'karma-phantomjs-launcher', 
  'karma-jasmine', 
  'karma-ng-html2js-preprocessor' 
], 

preprocessors: { 
  'app/views/*.html': ['ng-html2js'] 
}, 

ngHtml2JsPreprocessor: { 
  stripPrefix: 'app/', 
  moduleName: 'my.templates' 
},

Step 2: Use the module in your tests

// my-test.js

beforeEach(module("my.templates"));    // load new module containing templates

For a complete example, look at this canonical example from Angular test guru Vojta Jina. It includes an entire setup: karma config, templates, and tests.

A Non-Karma Solution

If you do not use Karma for whatever reason (I had an inflexible build process in legacy app) and are just testing in a browser, I have found that you can get around ngMock's takeover of $httpBackend by using a raw XHR to fetch the template for real and insert it into the $templateCache. This solution is much less flexible, but it gets the job done for now.

// my-test.js

// Make template available to unit tests without Karma
//
// Disclaimer: Not using Karma may result in bad karma.
beforeEach(inject(function($templateCache) {
    var directiveTemplate = null;
    var req = new XMLHttpRequest();
    req.onload = function() {
        directiveTemplate = this.responseText;
    };
    // Note that the relative path may be different from your unit test HTML file.
    // Using `false` as the third parameter to open() makes the operation synchronous.
    // Gentle reminder that boolean parameters are not the best API choice.
    req.open("get", "../../partials/directiveTemplate.html", false);
    req.send();
    $templateCache.put("partials/directiveTemplate.html", directiveTemplate);
}));

Seriously, though. Use Karma. It takes a little work to set up, but it lets you run all your tests, in multiple browsers at once, from the command line. So you can have it as part of your continuous integration system, and/or you can make it a shortcut key from your editor. Much better than alt-tab-refresh-ad-infinitum.

Solution 3

This initial problem can be solved by adding this:

beforeEach(angular.mock.module('ngMockE2E'));

That's because it tries to find $httpBackend in ngMock module by default and it's not full.

Solution 4

The solution I reached needs jasmine-jquery.js and a proxy server.

I followed these steps:

  1. In karma.conf:

add jasmine-jquery.js to your files

files = [
    JASMINE,
    JASMINE_ADAPTER,
    ...,
    jasmine-jquery-1.3.1,
    ...
]

add a proxy server that will server your fixtures

proxies = {
    '/' : 'http://localhost:3502/'
};
  1. In your spec

    describe('MySpec', function() { var $scope, template; jasmine.getFixtures().fixturesPath = 'public/partials/'; //custom path so you can serve the real template you use on the app beforeEach(function() { template = angular.element('');

        module('project');
        inject(function($injector, $controller, $rootScope, $compile, $templateCache) {
            $templateCache.put('partials/resources-list.html', jasmine.getFixtures().getFixtureHtml_('resources-list.html')); //loadFixture function doesn't return a string
            $scope = $rootScope.$new();
            $compile(template)($scope);
            $scope.$apply();
        })
    });
    

    });

  2. Run a server on your app's root directory

    python -m SimpleHTTPServer 3502

  3. Run karma.

It took my a while to figure this out, having to search many posts, I think the documentation about this should be clearer, as it is such an important issue.

Solution 5

My solution:

test/karma-utils.js:

function httpGetSync(filePath) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "/base/app/" + filePath, false);
  xhr.send();
  return xhr.responseText;
}

function preloadTemplate(path) {
  return inject(function ($templateCache) {
    var response = httpGetSync(path);
    $templateCache.put(path, response);
  });
}

karma.config.js:

files: [
  //(...)
  'test/karma-utils.js',
  'test/mock/**/*.js',
  'test/spec/**/*.js'
],

the test:

'use strict';
describe('Directive: gowiliEvent', function () {
  // load the directive's module
  beforeEach(module('frontendSrcApp'));
  var element,
    scope;
  beforeEach(preloadTemplate('views/directives/event.html'));
  beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
  }));
  it('should exist', inject(function ($compile) {
    element = angular.element('<event></-event>');
    element = $compile(element)(scope);
    scope.$digest();
    expect(element.html()).toContain('div');
  }));
});
Share:
70,462
Jesus is Lord
Author by

Jesus is Lord

1 Corinthians 15:3-4 For I delivered to you first of all that which I also received: that Christ died for our sins according to the Scriptures, and that He was buried, and that He rose again the third day according to the Scriptures Romans 10:9 that if you confess with your mouth the Lord Jesus and believe in your heart that God has raised Him from the dead, you will be saved Philippians 2:10 that at the name of Jesus every knee should bow, of those in heaven, and of those on earth, and of those under the earth

Updated on March 12, 2021

Comments

  • Jesus is Lord
    Jesus is Lord over 3 years

    Using AngularJS.

    Have a directive.

    Directive defines templateUrl.

    Directive needs unit testing.

    Currently unit testing with Jasmine.

    This recommends code like:

    describe('module: my.module', function () {
        beforeEach(module('my.module'));
    
        describe('my-directive directive', function () {
            var scope, $compile;
            beforeEach(inject(function (_$rootScope_, _$compile_, $injector) {
                scope = _$rootScope_;
                $compile = _$compile_;
                $httpBackend = $injector.get('$httpBackend');
                $httpBackend.whenGET('path/to/template.html').passThrough();
            }));
    
            describe('test', function () {
                var element;
                beforeEach(function () {
                    element = $compile(
                        '<my-directive></my-directive>')(scope);
                    angular.element(document.body).append(element);
                });
    
                afterEach(function () {
                    element.remove();
                });
    
                it('test', function () {
                    expect(element.html()).toBe('asdf');
                });
    
            });
        });
    });
    

    Running code in Jasmine.

    Getting error:

    TypeError: Object #<Object> has no method 'passThrough'
    

    templateUrl needs loading as-is

    Cannot use respond

    May be related to ngMock use rather than ngMockE2E use.

  • pbojinov
    pbojinov almost 11 years
    I was having trouble serving up assets from localhost/base/specs and adding a proxy server with python -m SimpleHTTPServer 3502 running fixed it. You sir are a genius!
  • Sam Simmons
    Sam Simmons almost 11 years
    I was getting an empty element returned from $compile in my tests. Other places suggested running $scope.$digest(): still empty. Running $scope.$apply() worked though. I think it was because I am using a controller in my directive? Not sure. Thanks for the advice! Helped!
  • Mat
    Mat over 10 years
    Well that's the correct answer to the original question indeed (that's the one that helped me).
  • Melbourne2991
    Melbourne2991 over 10 years
    I am getting Uncaught SyntaxError: Unexpected token <
  • Sten Muchow
    Sten Muchow about 10 years
    Here is my complaint with this method... Now if we are going to have a big piece of html that we are going to inject as a string into the template cache then what are we gonna do when we change the html on the front end? Change the html in the test as well? IMO that is an unsustainable answer and the reason we went with using the template over templateUrl option. Even though i highly dislike having my html as a massive string in the directive - it is the most sustainable solution to not having to update two places of html. Which doesnt take much imaging that the html can over time not match.
  • Johan
    Johan about 10 years
    This may be obvious, but if others get stuck on the same thing and look here for answers: I couldn't get it to work without also adding the preprocessors file pattern (e.g. "path/to/templates/**/*.html") to the files section in karma.conf.js.
  • Jackie
    Jackie almost 10 years
    So are there any major issues with not waiting for the response before continuing? Will it just update the value when the request comes back (I.E. takes 30 seconds)?
  • SleepyMurph
    SleepyMurph almost 10 years
    @Jackie I assume you're talking about the "non-Karma" example where I use the false parameter for the XHR's open call to make it synchronous. If you don't do that, the execution will merrily continue and start executing your tests, without having the template loaded. That gets your right back to the same problem: 1) Request for template goes out. 2) Test starts executing. 3) The test compiles a directive, and the template is still not loaded. 4) Angular requests the template through its $http service, which is mocked out. 5) The mock $http service complains: "unexpected request".
  • FlavorScape
    FlavorScape almost 10 years
    I was able to run grunt-jasmine without Karma.
  • Vincent
    Vincent over 9 years
    Another thing: you need to install karma-ng-html2js-preprocessor (npm install --save-dev karma-ng-html2js-preprocessor), and add it to the plugins section of your karma.conf.js, according to stackoverflow.com/a/19077966/859631.
  • Paul Sheldrake
    Paul Sheldrake over 9 years
    If you are using yeoman angular generator and karma, here is the config that worked for me // Which plugins to enable plugins: [ 'karma-phantomjs-launcher', 'karma-jasmine', 'karma-ng-html2js-preprocessor' ], preprocessors: { 'app/views/*.html': ['ng-html2js'] }, ngHtml2JsPreprocessor: { stripPrefix: 'app/', moduleName: 'templates' },
  • Les
    Les over 9 years
    First decent solution that does not try to force devs to use Karma. Why would angular guys do something so bad and easily avoidable in the middle of something so cool? pfff
  • Vincent
    Vincent over 9 years
    I'm unittesting a directive with a template using this method (karma + jasmine + ngHtml2JsPreprocessor) . The only problem is that the ng-if's are not compiled (even after scope.$digest()). Do you know how I can get the fully compiled html?
  • SleepyMurph
    SleepyMurph over 9 years
    @Vincent ngHtml2Js doesn't activate any directives or anything. It just converts the HTML to JS strings. So the ng-if attributes in your HTML should surely be present in the Angular template. Is the problem that they're not taking effect? If so, double-check the "if" expression to make sure it really has the value you expect. Also, keep in mind that unlike ng-show, ng-if actually removes the elements from the DOM when the expression is false, and recreates them when it's true. So if the elements are missing from the DOM, that could just mean it's working.
  • chfw
    chfw over 9 years
    Have to down-vote it because the first karma solution does not work for me. the non-karma solution works but it costs me 2h to realize the first work does not work. @bartek's solution is much better than the non-karma solution in this answer.
  • Roar Skullestad
    Roar Skullestad over 9 years
    Remember to do scope.$digest() to load the templates.
  • Stephane
    Stephane about 9 years
    I see you add a 'test/mock/**/*.js' and I suppose it is to load all the mocked stuff like services and all ? I'm looking up for ways to avoid code duplication of mocked services. Would you show us a bit more on that ?
  • bartek
    bartek about 9 years
    don't remember exactly, but there were problably settings for example JSONs for $http service. Nothing fancy.
  • lwalden
    lwalden about 9 years
    Had this problem today - great solution. We use karma but we also use Chutzpah - no reason we should be forced to use karma and only karma to be able to unit test directives.
  • markS
    markS almost 9 years
    after searching for about 20 minutes came across this solution ... went to start configuring my karma.conf file but since I'm using yeoman (github.com/Swiip/generator-gulp-angular) this preprocessor was already installed / configured ... all i had to do was add beforeEach(module("my.templates")); ... substituting my.templates and i was done! thanks!
  • Aleck Landgraf
    Aleck Landgraf over 8 years
    We're using Django with Angular, and this worked like a charm to test a directive that loads its templateUrl though static, e.g. beforeEach(preloadTemplate(static_url +'seed/partials/beChartDropdown.html')); Thanks!
  • frodo2975
    frodo2975 over 8 years
    Tried this, but passThrough() still didn't work for me. It still gave the "Unexpected request" error.
  • Rahul Patel
    Rahul Patel over 8 years
    @chfw Did you call $scope.$digest() after the call to $compile? I just spent probably the same amount of time trying to figure out why the template HTML wasn't loading until I realized I was missing that.
  • Winnemucca
    Winnemucca over 8 years
    I got ) ReferenceError: XMLHttpRequest is not defined ReferenceError: XMLHttpRequest is not defined. Not sure how others got this to work.
  • SleepyMurph
    SleepyMurph over 8 years
    @stevek That is very strange. XMLHttpRequest is a very old piece of browser API that should be present in all modern (and not so modern) browsers. If you are running that test code on a page in a browser, XMLHttpRequest should be defined. The simplest explanation would be a typo. Are you sure it's spelled and capitalized correctly? Also, XMLHttpRequest is part of the browser API, but not part of the core language. So non-browser JS engines like NodeJS don't have it. Is it possible your setup is trying to run the test in Node itself rather than launching a browser to run the test?
  • Winnemucca
    Winnemucca over 8 years
    yeah, I believe that is the case. We are trying out some simple tests with jsdom.
  • Winnemucca
    Winnemucca over 8 years
    Can you do this without Karma?
  • kam
    kam almost 8 years
    is it possible to use a path like below. eg using ../../../ It doesn't work for me with dots in the path. "../../../path/to/templates/**/*.html": ["ng-html2js"] stripPrefix: '../.././path', Thanks