Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
scenario, a describe wrapper for mocha tests

When testing a server, there can be a lot of redundant code for setting up common fixtures in every test of every route. To avoid this problem, we are exploring using a scenario function which is similar to describe but runs default actions (e.g. setting up database fixtures, starting fake servers) and is configurable via options.

Example usage:

var scenario = require('./scenario');

scenario('A request to GET /', function () {
  it('has no errors', function () {
  
  });
});

scenario.skip('A request to GET /pending', function () {
  it('has no errors', function () {
  
  });
});

scenario('A request to GET / with fixtures', {
  dbFixtures: ['user-default']
}, function () {
  it('has no errors', function () {
  
  });
});
// Load in our dependencies
var _ = require('underscore');
// Define all-in-one describe handler
function _scenario(key, describeStr, options, describeFn) {
// If there is no describe function, then assume it was options
// `scenario('A request ...', function () {})` -> `scenario('A request ...', {}, function () {})`
if (describeFn === undefined) {
describeFn = options;
options = {};
}
// Set up default options
options = _.extend({
// Default options go here
// dbFixtures: dbFixtures.DEFAULT_FIXTURES,
// googleFixtures: fakeGoogleFactory.DEFAULT_FIXTURES
}, options);
// Call describe function (e.g. `describe`, `describe.skip`)
// on context of describe object
function scenarioFn() {
// Before/after hooks for `scenario` go here (e.g. installing fixtures, starting servers)
// before(function () { ... });
// Run describe actions
describeFn.call(this);
}
// Call Mocha's describe function (e.g. `describe`, `describe.only`)
if (key) {
describe[key](describeStr, scenarionFn);
} else {
describe(describeStr, scenarionFn);
}
}
module.exports = function (describeStr, options, describeFn) {
_scenario(null, describeStr, options, describeFn);
};
module.exports.only = function (describeStr, options, describeFn) {
_scenario('only', describeStr, options, describeFn);
};
module.exports.skip = function (describeStr, options, describeFn) {
_scenario('skip', describeStr, options, describeFn);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment