Skip to content

Instantly share code, notes, and snippets.

@maxnordlund
Last active May 2, 2019 11:44
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 maxnordlund/a860dd67013beaf0f31ce776536f0a47 to your computer and use it in GitHub Desktop.
Save maxnordlund/a860dd67013beaf0f31ce776536f0a47 to your computer and use it in GitHub Desktop.
ESM in Mocha
// Disable stealthy-require as it breaks ESM in modernish node
// 1. Load stealthy-require into the require cache. This way all the module
// machinery gets run like normal.
require("stealthy-require")
// 1. Overwrite the real function with a dummy one
require.cache[require.resolve("stealthy-require")].exports = notSoSthealthyRequire
// 3. Dummy implementation that calls the provided callbacks in the right order
// but doesn't do anything fancy to the require cache.
function notSoSthealthyRequire(_requireCache, callback, callbackForModulesToKeep, _module) {
callbackForModulesToKeep()
return callback()
}
import "./_disable_stealthy_require.js"
import path from "path"
import Mocha from "mocha/lib/mocha"
const { run: originalRun } = Mocha.prototype
Mocha.prototype.run = async function ESM$run(_fn) {
let { suite } = this
for (let [index, file] of this.files.entries()) {
file = path.resolve(file)
suite.emit("pre-require", global, file, this)
suite.emit("require", await import(file), file, this)
suite.emit("post-require", global, file, this)
}
return originalRun.apply(this, arguments)
}
Mocha.prototype.loadFiles = function ESM$loadFiles(fn) {
// The real work has already been done in `run` above
fn && fn()
}
import cli from "mocha/lib/cli/cli"
cli.main()
#!/bin/sh
set -e
dir=$(CDPATH="" cd -- "$(dirname -- "$0")" && pwd)
mocha="$dir/_mocha.mjs"
export NODE_ENV=test
export PATH="$dir/../node_modules/.bin":$PATH
# Generate both a report to the terminal, with summary, and a HTML for details.
c8 node --experimental-modules "$mocha" "$@"
#!/bin/sh
set -e
dir=$(CDPATH="" cd -- "$(dirname -- "$0")" && pwd)
mocha="$dir/_mocha.mjs"
export NODE_ENV=test
node --inspect=9230 --experimental-modules "$mocha" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment