0

I'm new to Webpacker and Rails in general. I recently moved to using Webpacker to bundle React components. Since part of the application still uses the asset pipeline, some dependencies are still stored in vendor/assets/javascript, and accessible as globals. The Webpack bundle declares those dependencies as external, and when serving the app, everything works great, as Rails serves the dependencies, which are then picked up by the bundle. Now I want to start testing the bundle using something like jsdom. I'm using mocha-webpack with the same config as in development.

How can I load the external dependencies in this case? If I understand correctly, the bundle builds fine, but when the tests run, the dependencies are not loaded.

2 Answers2

0

Consider using another webpack.config.js just for the test build, e.g. create a webpack.config.test.js that does not use externals, but bundles all vendor files as npm dependencies.

  • See also: https://stackoverflow.com/questions/45724728/enzyme-unit-tests-with-webpack-externals – Luke H Jul 29 '21 at 01:34
0

I used webpack's resolve.alias feature in test mode and the externals feature in development/production mode.

Basically, make your webpack.config.js check process.env.NODE_ENV and return different settings depending on the mode.

const path = require('path');

const isTest = process.env.NODE_ENV === 'test';

let resolve;
let externals = { jquery: 'jquery ' };
if (isTest) {
    externals = {};

    resolve = {
        alias: {
            // you may have to fiddle around with this path, from the point of view of where jquery is imported
            jquery: './tests/helpers/fakeJQuery.js',
        }
    };
}

module.exports = {
    // ...
    resolve,
    externals,
    // ...
};

An example of this for vue.js can be seen here: https://stackoverflow.com/a/68569055/289203

Luke H
  • 3,125
  • 27
  • 31