Skip to content

Instantly share code, notes, and snippets.

@vucalur
Last active September 22, 2016 20:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vucalur/7238489 to your computer and use it in GitHub Desktop.
Save vucalur/7238489 to your computer and use it in GitHub Desktop.
Yeoman - AngularJS : karma configuration for directives testing
// file: app/scripts/directives/myDirective.js
angular.module('someApp.directive').directive('myDirective', function () {
return {
templateUrl: 'templates/myDirective.html', // HERE
....
}
});
// file: karma.conf.js
// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/scripts/*.coffee',
'app/scripts/**/*.coffee',
'test/mock/**/*.coffee',
'test/spec/**/*.coffee',
'app/templates/**/*.html' // HERE
],
preprocessors: {
'**/*.coffee': 'coffee',
'app/templates/**/*.html': 'ng-html2js' // HERE
},
ngHtml2JsPreprocessor: {
// strip this from the file path
stripPrefix: 'app/' // HERE
},
autoWatch: true,
...
});
};
// file: test/spec/directives/myDirective.js
describe('Directive: myDirective', function() {
var element, scope;
beforeEach(module('someApp.directive'));
beforeEach(module('templates/myDirective.html', 'templates/myDirective.html')); // HERE. load module prepared by ng-html2js
beforeEach(inject(function($compile, $rootScope) {
scope = $rootScope.$new();
// prepare scope in which your directive should be used
// ...
element = angular.element('<myDirective></myDirective>');
$compile(element)(scope);
scope = element.scope();
return scope.$apply();
}));
it('fancy-dancy test', inject(function($compile) {
expect(element.text()).toBe('...');
}));
});
@pandeiro
Copy link

pandeiro commented Nov 6, 2013

Hi, thanks for posting this. I'm tearing my hair out trying to test external templates with Karma.

One thing I didn't understand is where this came from:

files: [
  ...
  'app/directiveTemplates/**/*.html'
]

Is that a directory created by ng-html2js?

@vucalur
Copy link
Author

vucalur commented Jun 25, 2014

sorry for a lag with the response,
should be app/templates/**/*.html. Edited the gist

Initially I had two different directories: one for 3rd party templates, populated with grunt task after downloading them with bower, the other for my templates, hence the mistake.

@zorec
Copy link

zorec commented Jul 5, 2014

I had to do one more step to make it work in karma.conf.js:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment