实际上这里的问题完全相同,但上下文不同: How to mock not installed npm package in jest?
我是从 webpack 使用新模块联合的项目的一部分。基本上,我有一个主机应用程序,它使用远程应用程序。我在这里为路由做同样的事情: https ://github.com/module-federation/module-federation-examples/tree/master/shared-routes2
我的主机应用程序导入远程应用程序的路由类似(我从模块联合存储库中获取了这个示例:https ://github.com/module-federation/module-federation-examples/blob/master/shared-routes2/app1/ src/App.js )
// app1/src/App.js
import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import localRoutes from "./routes";
import remoteRoutes from "app2/routes";
const routes = [...localRoutes, ...remoteRoutes];
const App = () => (
<BrowserRouter>
<div data-test-id="App-navigation">
<h1>App 1</h1>
<React.Suspense fallback={<div>Loading...</div>}>
<Switch>
{routes.map((route) => (
<Route
key={route.path}
path={route.path}
component={route.component}
exact={route.exact}
/>
))}
</Switch>
</React.Suspense>
</div>
</BrowserRouter>
);
我的这个组件的测试文件如下所示:
// app1/src/App.test.js
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import App from './App';
jest.mock('app2/routes');
describe('App', () => {
test('should render navigation', async () => {
const { findByTestId } = render(
<MemoryRouter>
<App />
</MemoryRouter>,
);
const app = await findByTestId('App-navigation');
expect(drawerMenu).toBeInTheDocument();
});
});
该测试按原样产生错误:
❯ yarn test App.test.js
yarn run v1.22.10
$ jest App.test.js
FAIL src/App.test.js
● Test suite failed to run
Cannot find module 'app2/routes' from 'src/App.test.js'
6 | import App from './App';
7 |
> 8 | jest.mock('app2/routes');
| ^
9 |
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:306:11)
at Object.<anonymous> (src/App.test.js:8:6)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 3.78 s
Ran all test suites matching /App.test.js/i.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
我相信会发生此错误,因为实际上没有名为app2/routes
. 它是由 webpack 模块联合插件生成的联合模块。但是,jest
在模拟它之前寻找实际的模块。
这是我被卡住并且没有想法的部分。
任何建议高度赞赏。
更新:
Jest 提供虚拟模拟,它解决了我的问题。(我从这个答案中找到了解决方案:https ://stackoverflow.com/a/56052635/5018572 )
jest.mock('app2/routes',
() => {
// some mocking for my remote app routes
},
{ virtual: true }
);
完成后mocking factory
,您只需传递{ virtual: true }
选项并开玩笑停止抱怨模块的存在。
希望它对遇到同样问题的人有所帮助。