Skip to content

Instantly share code, notes, and snippets.

@zbjornson
Last active March 10, 2019 19:59
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 zbjornson/3dd7be429358540db61426d2e14176ce to your computer and use it in GitHub Desktop.
Save zbjornson/3dd7be429358540db61426d2e14176ce to your computer and use it in GitHub Desktop.
Jest gotchas
/**
* Jest's require() cache is reset between tests (modules are re-evaluated)
* for most, but not all modules. In the "not all" group are native modules,
* so all interactions with them must be idempotent.
* https://github.com/facebook/jest/issues/4413
*
* Encountered in https://github.com/Automattic/node-canvas/issues/1310,
* https://github.com/Automattic/node-canvas/issues/1294,
* https://github.com/Automattic/node-canvas/issues/1250
*/
const nativemodule = require("build/Release/something.node");
// next two lines are not idempotent
const privateMethod = nativemodule.doSomething;
delete nativemodule.doSomething;
// (privateMethod is used here for something)
module.exports = nativemodule;
/**
* In the same vein as above, Node.js's core modules like `process` are in
* the "not all" group so e.g. attaching event listeners creates leaks and
* other unexpected behaviors.
*
* Encountered in https://github.com/siimon/prom-client/pull/147#issuecomment-326782465
*/
process.on("message", msg => {
// a new listener is attached every time this module is required
// and jest has reset its require() cache.
});
@zbjornson
Copy link
Author

zbjornson commented Feb 1, 2019

Other possible issues similar to above: modules that open file descriptors, open sockets or set timeouts/intervals.

Additionally, jest relies on some properties being configurable. Breakages this has caused:

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