Skip to content

Instantly share code, notes, and snippets.

@twolfson
Created November 16, 2016 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twolfson/1ddf42a41bffefb8c2f298c082e4a337 to your computer and use it in GitHub Desktop.
Save twolfson/1ddf42a41bffefb8c2f298c082e4a337 to your computer and use it in GitHub Desktop.
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);
};
@caseyduquettesc
Copy link

Typo on line 32 & 34, scenarionFn -> scenarioFn

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