Alfred
Alfred

Reputation: 447

How can I make webpack externals available to jest

My jest test is failing on import config from "config" with the error cannot find module, config is a webpack external set like this:

const { environment } = require('@rails/webpacker');
customConfig = {
  development: {
    externals: { config: { name: "Something", apiURL: "localhost:3000/api" } }
  }
};
environment.config.merge(customConfig.development) and then module.exports = environment.toWebpackConfig();

How can I make this accessible to jest so the test doesn't fail;

Upvotes: 1

Views: 413

Answers (1)

Teneff
Teneff

Reputation: 32158

You can create a virtual mock for non-existing module in file like this:

./config.jest.setup.js
jest.mock('config' () => ({
    name: "Something",
    apiURL: "localhost:3000/api"
}), {
  virtual: true
});

and load it in setupFilesAfterEnv

package.json
{
  // ... rest of the package
  "jest": {
    "setupFilesAfterEnv": ["./config.jest.setup.js"]
  }
}

Upvotes: 1

Related Questions