npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

babel-plugin-explicit-exports-references

v1.0.2

Published

Transforms all internal references to a module's exports such that each reference starts with `module.exports` instead of directly referencing an internal name. This enables easy mocking of specific (exported) functions in Jest with Babel/TypeScript, even

Downloads

22,446

Readme

Black Lives Matter! Maintenance status Last commit timestamp Open issues Pull requests codecov Source license NPM version semantic-release

babel-plugin-explicit-exports-references

Transforms all internal references to a module's exports such that each reference starts with module.exports instead of directly referencing an internal name. This enables easy mocking of specific (exported) functions in Jest with Babel/TypeScript, even when the mocked functions call each other in the same module.

Installation and Usage

npm install --save-dev babel-plugin-explicit-exports-references

And in your babel.config.js:

module.exports = {
  plugins: ['explicit-exports-references']
};

Note: it is recommended that this plugin only be enabled when NODE_ENV is test. Using this plugin elsewhere, such as in production, can lead to increased build size. For example:

module.exports = {
  parserOpts: { ... },
  plugins: [ ... ],
  env: {
      test: {
        plugins: ['explicit-exports-references']
      }
  }
};

Finally, run Babel through your toolchain (Webpack, Jest, etc) or manually:

npx babel src --out-dir dist

AST Algorithm

To see detailed output on how this plugin transforms your code, enable debug mode: DEBUG='babel-plugin-explicit-exports-references:*' npx jest your-test-file

The plugin begins by looking for default and named export declarations in a program.

For default exports, it looks for function declarations and class declarations that have ids (i.e. variable names), like export default function main() {}, and updates any Identifiers referencing that id.

For named exports, it looks for function and class declarations too, but also variable declarations like export const foo = 5; and export { x as default, y, x as z };. Enums are explicitly ignored. Any Identifiers that reference the declaration's id or specifier are updated.

When updating references, by default only Identifiers are transformed. Assignment Expressions can also be transformed, but doing so is currently unstable. All other reference types are ignored, including TypeScript types and Identifiers within their own declarations.

The following enables transforming Assignment Expressions along with Identifiers:

module.exports = {
  plugins: [
    ['explicit-exports-references', { transformAssignExpr: true }]
  ]
};

Motivation

Suppose we have the following myModule.ts TypeScript file:

// file: myModule.ts

export function foo() {
  // This function works fine in production but throws on our local test machine
  throw new Error('failed to do expensive network stuff');
  return;
}

export function bar() {
  // ...
  foo();
  return 5;
}

export function baz() {
  // ...
  foo();
  return 50;
}

Lets say we want to unit test myModule.ts. Specifically, we want to test bar and baz. We don't want to unit test foo because a) attempting to run it on our local machine will always fail, which is why b) it is covered by our integration tests instead. We simply want to ensure bar and baz work, and that they both call foo without running foo.

If we expect a function to be called, and we want an alternative implementation run when it is called, the easy and obvious solution is to mock it.

So suppose we create the following myModule.test.ts Jest test file, mocking foo with a noop:

// file: myModule.test.ts

import * as myModule from './myModule';

it('bar does what I want', () => {
  const spy = jest.spyOn(myModule, 'foo').mockImplementation(() => undefined);

  expect(myModule.bar()).toBe(5);
  expect(spy).toBeCalled();

  spy.mockRestore();
});

it('baz does what I want', () => {
  const spy = jest.spyOn(myModule, 'foo').mockImplementation(() => undefined);

  expect(myModule.baz()).toBe(50);
  expect(spy).toBeCalled();

  spy.mockRestore();
});

This file tests that bar and baz do what we want, and whenever they call foo the dummy version is called instead and no error is thrown. Or rather, that seems like it should be the thing that happens. Unfortunately, if we run this code, the above tests will fail because foo throws failed to do expensive network stuff.

Is this a bug?

After encountering this problem over five years ago, someone posed the question to the Jest project: how do you mock a specific function in a module?, to which a contributor responded:

Supporting the above by mocking a function after requiring a module is impossible in JavaScript – there is (almost) no way to retrieve the binding that foo refers to and modify it.

However, if you change your code to this:

var foo = function foo() {};
var bar = function bar() {
  exports.foo();
};

exports.foo = foo;
exports.bar = bar;

and then in your test file you do:

var module = require('../module');
module.foo = jest.fn();
module.bar();

it will work just as expected. This is what we do at Facebook where we don't use ES2015.

While ES2015 modules may have immutable bindings for what they export, the underlying compiled code that babel compiles to right now doesn't enforce any such constraints. I see no way currently to support exactly what you are asking...

Essentially, this plugin aims to automate the suggestion above, allowing you to mock a specific module function using standard Jest spies by automatically replacing references to exported identifiers with an explicit reference of the form module.exports.${identifier}. No assembly required.

With this plugin loaded into Babel, the tests in the motivating example above pass! 🎉

Prior Art

Prior solutions include:

Further reading and additional solutions:

  • https://medium.com/@DavideRama/mock-spy-exported-functions-within-a-single-module-in-jest-cdf2b61af642
  • https://medium.com/@qjli/how-to-mock-specific-module-function-in-jest-715e39a391f4
  • https://kennethteh90.medium.com/jest-how-to-mock-functions-that-reference-each-other-from-the-same-module-9f1d3293ec81
  • https://github.com/facebook/jest/issues/936

Documentation

Further documentation can be found under docs/.

Contributing and Support

New issues and pull requests are always welcome and greatly appreciated! 🤩 Just as well, you can star 🌟 this project to let me know you found it useful! ✊🏿 Thank you!

See CONTRIBUTING.md and SUPPORT.md for more information.