Skip to content

Instantly share code, notes, and snippets.

@ynonp
Created October 23, 2013 08:57
Show Gist options
  • Save ynonp/7115044 to your computer and use it in GitHub Desktop.
Save ynonp/7115044 to your computer and use it in GitHub Desktop.
A small library for handling fixtures in Mocha unit tests
function Fixtures(opts) {
var self = this;
opts = opts || {};
self.base = opts.base ? opts.base : "";
self._cache = {};
self.fixture_id = opts.fixture_id || "fixture";
self.el;
return {
load: function(htmlFile, done) {
// given an htmlFile name, try to load it from the server
// and insert the result into a cache
// for later injection
var xhr = new XMLHttpRequest();
xhr.open("GET", self.base + htmlFile);
xhr.onload = function(e) {
if ( this.status == 200 ) {
self._cache[htmlFile] = this.response;
self.last_loaded_filename = htmlFile;
done();
}
else {
done('error loading page: ' + this.status);
}
};
xhr.onerror = done;
xhr.send();
},
inject: function(htmlFile) {
// if no file was requested, try the last loaded file
if ( ! htmlFile ) htmlFile = self.last_loaded_filename;
// but if no file was ever loaded, throw an exception
if ( ! htmlFile ) throw "Can't inject before load";
// Inject the fixture into the DOM under a special div
self.el = document.getElementById(self.fixture_id);
if ( ! self.el ) {
self.el = document.createElement('div');
self.el.id = self.fixture_id;
document.body.appendChild(self.el);
}
self.el.innerHTML = self._cache[htmlFile];
},
cleanup: function() {
// empty the fixture div
self.el = document.getElementById(self.fixture_id);
if ( self.el ) {
self.el.innerHTML = '';
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment