Can not use resolve.alias for JEST testing
我正在为应用程序使用WebPack React Jest,并且已经在配置文件中设置了
在React中,我可以使用此路径执行require(" app / component ")并正确获取" / path / to / app / component.js "中的文件。
在运行JEST测试时,无论在测试中还是对于导入的模块,都无法识别此别名。所有这些在运行应用程序时均有效,但对jest-cli的测试无效。
使用babel-plugin-module-resolver处理别名。
我使用摩卡咖啡测试反应,但我认为这也很有趣。
您应该使用2个软件包:mock-require和proxyquire。
假设您有一个这样的js文件:
app.js
1 2 3 | import action1 from 'actions/youractions'; export function foo() { console.log(action1()) }; |
您的测试代码应如下所示:
app.test.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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', () => { ... }); }); |
文件树
1 2 3 | app.js |- test |- app.test.js |
首先在before函数中通过mock-require模拟别名路径,然后在beforeEach函数中通过proxyquire模拟您的测试对象。?pb>
Jestpack可能会有所帮助,因为它使您可以在使用Webpack构建测试之后运行它们。