robertknight / babel-plugin-mockable-imports

Babel plugin that enables mocking of ES and CommonJS imports in tests
12 stars 1 forks source link

Make it a babel macro to support zero-config environments #33

Open AndyOGo opened 3 years ago

AndyOGo commented 3 years ago

With Babel 7 babel-plugin-macros is enabled by default.

It would be cool if one could just use a zero-config bundler like parcel or a starter like create-react-app without the need to change the actual babel config. https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros

// this line activates the babel-marco directly in my test file
import importMockable from 'babel-plugin-mockable-imports.macro';

importMockable('./file-to-be-tested');

// ... do the other testing stuff as usual
robertknight commented 3 years ago

In order for this plugin to work it needs to run inside the file being tested, rather than in the file containing the tests. You can see why if you inspect the generated code. Usage of this plugin is similar to a code coverage plugin - it needs to modify the code being tested and it should only be used when processing the code for a test run, to avoid adding useless code to production builds.

Is the above possible with Babel macros?

AndyOGo commented 3 years ago

You have full access to the AST of that particular file. So you could provide a special importMockable function and transform that imported file, like import-all macro does (I updated my example above). https://github.com/kentcdodds/import-all.macro

With such a custom importMockable function call you get full control of which babel plugins to run on that file.

More awesome macro examples can be found here: https://github.com/jgierer12/awesome-babel-macros

Details about the Macro API are here: https://github.com/kentcdodds/babel-plugin-macros/blob/main/other/docs/author.md#function-api

Macros execute in order: https://github.com/kentcdodds/babel-plugin-macros#in-what-order-are-macros-executed