Reputation: 307
I am using WebPack + React + Jest for my application and I have set resolve.alias = { app: "/path/to/app" }
in my configuration file.
In React, I can use this path to do require("app/component") and obtain the file at "/path/to/app/component.js" correctly.
When running JEST tests this alias is not recognized, neither in the tests, nor for the imported modules. All of this works when running the app but not the tests with jest-cli.
Upvotes: 10
Views: 3412
Reputation: 26873
jest-cli
lives in a world separate from Webpack so it cannot work that way.
Use babel-plugin-module-resolver to handle aliasing.
Upvotes: 4
Reputation: 645
I use mocha to test react, but I think it also work for jest.
You should use 2 package: mock-require and proxyquire.
Assuming you have a js file like this:
app.js
import action1 from 'actions/youractions';
export function foo() { console.log(action1()) };
And your test code should write like this:
app.test.js
import proxyquire from 'proxyquire';
import mockrequire from 'mock-require';
before(() => {
// mock the alias path, point to the actual path
mockrequire('actions/youractions', 'your/actual/action/path/from/your/test/file');
// or mock with a function
mockrequire('actions/youractions', {actionMethod: () => {...}));
let app;
beforeEach(() => {
app = proxyquire('./app', {});
});
//test code
describe('xxx', () => {
it('xxxx', () => {
...
});
});
files tree
app.js
|- test
|- app.test.js
First mock the alias path by mock-require in before function, and mock your test object by proxyquire in beforeEach function.
Upvotes: 0
Reputation: 7033
Jestpack might help as it will allow you to run your tests after they've been built with Webpack.
Upvotes: 0