jeudi 20 août 2015

Angular Unit Testing Directives with External Templates

I am getting an error trying to compile a directive for testing. I'm using Karma and chai for executing my tests and my config is set up as follows:

  karma.conf.js ---
    module.exports = function(config) {
    config.set({
    frameworks: ['browserify', 'mocha', 'chai'],

    files: [
          'node_modules/jquery/dist/jquery.js',
          'node_modules/angular/angular.js',
          'node_modules/angular-mocks/angular-mocks.js',
          'src/main/webapp/dev/templates/templates.js',
          'src/main/webapp/dev/js/components/**/*.js',
          'src/main/webapp/dev/js/modules/**/*.js',
          'src/test/js/**/*-test.js',
          'src/main/webapp/dev/templates/**/*.html'
        ],

    ngHtml2JsPreprocessor: {
      stripPrefix: 'src/main/webapp/dev/templates/',
      'moduleName': 'htmlTemplates'
    },

    browsers: ['PhantomJS'],

    plugins: [
    'karma-browserify',
    'karma-chai',
    'karma-mocha',
    'karma-phantomjs-launcher',
    'karma-chrome-launcher',
    'karma-ng-html2js-preprocessor'
    ],

    preprocessors: {
      'src/main/webapp/dev/js/components/**/*.js': ['browserify'],
      'src/main/webapp/dev/js/modules/**/*.js': ['browserify'],
      'src/test/js/**/*-test.js': ['browserify'],
      'src/main/webapp/dev/templates/**/*.html': ['ng-html2js']
    },

    });
    };

I'm stripping the absolute path from the html modules created via html2js so they align with how my directive is calling for the templateUrl.
My directive is setup with:

directive.js ----
function() {
  return {
    restrict: 'E',
    scope: {},
    controller: directiveController,
    templateUrl: "components/directive-folder/directive.html",
    link: function....

and finally my test is configured as:

directive-test.js ----
var expect = require('chai').expect;

beforeEach(angular.mock.module('directive.module'));
beforeEach(angular.mock.module('htmlTemplates'));

beforeEach(inject(function(_$rootScope_, _$compile_){
    $rootScope = _$rootScope_;
    $compile = _$compile_;

    $scope = $rootScope.$new();

    var directiveHtml = '<directive></directive>';

    var directiveElem = angular.element(directiveHtml);

    $compile(directiveElem)($scope);
    $scope.$digest();

  }));

  it('should compile', function() {
    expect()....
  });

The Error is thrown when calling $scope.$digest() (or $rootScope.$digest, etc). That is, all my tests "pass" when I do not run a digest cycle.

This is the actual error Karma is logging to the console:

"message": "[ng:areq] Argument 'fn' is not a function, got Object

when I log my "compiled" directive element I just get

"<directive class='ng-scope'></directive>" 

as if Angular compiled the node but wasn't able to find the template required.

Is there something wrong in my setup? Or is there something else entirely I'm missing?

Aucun commentaire:

Enregistrer un commentaire