Skip to content
Jim Chen edited this page May 16, 2019 · 4 revisions

Jasmine Templates

grunt-contrib-jasmine allows you to specify your own templates in order to customize your runs. You can and are encouraged to package up your templates as node modules for others to use. The only requirement is that your NPM module exports an object with a process method.

process method

You can expect 3 parameters passed to your template's process method: grunt task and context

  • grunt - the current grunt context
  • task - a grunt-contrib-jasmine object exposing useful methods
  • context - the context your template is being passed

Example template processor

This template does nothing more than execute a template as an underscore template with the given context

var template = __dirname + '/my_template.tmpl';

exports.process = function(grunt, task, context) {
  var source = grunt.file.read(template);
  return grunt.util._.template(source)(context);
};

Task methods

These methods are available off the task parameter.

copyTempFile(src, dest);

Copies a file into the task's temporary directory allowing you to easily refer to the file in your template. Useful for packaging 3rd party libraries into a distributable module and accessing them via a jasmine specrunner.

var template = __dirname + '/my_template.tmpl';

var myLibrary = __dirname + '/my_library-1.0.0.js'

exports.process = function(grunt, task, context) {

  task.copyTempFile(myLibrary, 'myLibrary.js');
  var source = grunt.file.read(template);
  return grunt.util._.template(source)(context);
};

This file can now be referred to in your template, e.g.

<script src="<%= temp %>/myLibrary.js"></script>

writeTempFile(dest, contents);

Writes contents to a file placed into the temporary directory.

eventDispatcher:EventEmitter (Proposed)

An EventEmitter instance that contains all events invoked through window.sendMessage inside the sandbox. Templates can send and receive custom messages by properly setting up the template and hooking listeners here.

template.tmpl:

...
<script src="text/javascript">(function () {
  window.sendMessage('mytemplate.mymessage', 'Hello World!');
})()</script>
...

template.js

exports.process = function(grunt, task, context) {
  var source = grunt.file.read(template);
  task.eventDispatcher.on('mytemplate.mymessage', function (message) {
    console.log(message); // Logs "Hello World!"
  });
  return grunt.util._.template(source)(context);
};