How to compile test-only code with webpack

Refresh

5 weeks ago

Views

49 time

1

I have a few private methods that I want to write unit tests for. However, since these are private methods, they are not exported.

This article shows how you can use grunt to wrap a code in comments and this code will be excluded from compiling if you are compiling for production.

Is there a similar thing for Webpack? Basically I want something so I can do something like

/* test-only */
export {_myPrivateMethod};
/* end-test-only */

And this code will be excluded from the final compiled, but will be included when running tests.

1 answers

0

Ideally, you would not test private functions directly. It is better to gain the coverage of those functions by executing them via your public API. http://www.peterprovost.org/blog/2012/05/31/my-take-on-unit-testing-private-methods

However, if you really wanted to, you could perform a production build to optimize out the code that you wanted to omit. It would look something like this:

if (process.env.NODE_ENV !== 'production') {
    // this code will not appear in a production build
}

This works because webpack automatically defines process.env.NODE_ENV when you do a production build and will be optimized out of the bundle. If you wanted to get fancy, you could define your own variables using the DefinePlugin and do a similar check.

You can read more here: https://webpack.js.org/guides/production/ and here: https://webpack.js.org/plugins/define-plugin/