Skip to content

Instantly share code, notes, and snippets.

@JonDotsoy
Last active May 7, 2019 13:33
Show Gist options
  • Save JonDotsoy/f3a1f954e66e803f9552c02959a0a82d to your computer and use it in GitHub Desktop.
Save JonDotsoy/f3a1f954e66e803f9552c02959a0a82d to your computer and use it in GitHub Desktop.
This is a function to create an asynchronous helper. This helps for helpers that perform mocha, db preparers, among others.

Create helper asynchronous to Mocha

This is a function to create an asynchronous helper. This helps for helpers that perform mocha, db preparers, among others.

How does it work

It stops Mocha#rut() preventing the upload of the files. it execute an asynchronous function and the continues with the mocha loader.

How to install

Copy this chunk in your helper

Prefer in the end of the file.

function preloadMocha(asyncFn) {
  const Mocha = require('mocha/lib/mocha');
  const run = Mocha.prototype.run;
  Mocha.prototype.run = function preRun(...args) {
    Promise.resolve(asyncFn()).then(() => {
      return run.apply(this, args);
    });
  };
}

Sample

// helper.js
const sanbox = sinon.createSandbox();
const mongod = new MongoMemoryServer();

preloadMocha(async () => {
  const mongouri = await mongod.getConnectionString();
  sanbox.replace(process.env, 'MONGO_URI', mongouri);
});

Load with mocha

$ mocha -r helper.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment