我有两个微正面(用react &打字本写)。仪表板MFE和通用MFE
通用MFE有多个组件,可由仪表板独立使用。例如:通知组件,加载程序组件等.
dashboard.component.tsx和简化的MFE1版本如下所示,
import React from react
....
....
import notificationComponent from 'common/NotificationComponent' <<====This is external module or component
// and several other component which are part of common micro frontend
const DashboardComponent = () => {
...
...
...
return (<div>
<notificationComponent .../>
....
</div>)
}
export default DashboardComponent;
我在remoteTypes.d.ts文件中定义了它的类型如下,
src/remoteTypes.d.ts
declare module 'common/NotificatioComponent' {
const NotificatioComponent: React.ComponentType<{ notification: { title: string, description: string, color: string } }>;
export default NotificatioComponent;
}
这很好用。
问题在于用jest和酶对仪表板组件进行单元测试。
当我写和运行一个简单的测试时,
test('dashboard component',()=>{
const wrapper = mount(
<Provider store={myStore}>
<Router>
<DashboardComponent />
</Router>
</Provider>
)
})
它抛出错误如下,
无法从“src/components/dashboard.Component.tsx”中找到“公共/NotificationComponent”模块
需要堆栈:
/components/dashboard.Component.tsx
/components/dashboard.Component.text.tsx
我应该如何解决这个错误?
我正在导出通知组件如下,
webpackage.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { ModuleFederationPlugin } = require('webpack').container;
const path = require('path');
const deps = require('./package.json').dependencies;
const Dotenv = require('dotenv-webpack');
module.exports = {
entry: './src/index.ts',
...
....
plugins: [
new ModuleFederationPlugin({
name: 'common',
filename: 'remoteEntry.js',
exposes: {
// expose each component
'./CommonBootstrap':'./src/bootstrap',
'./NotificationComponent': './src/components/notification/components/notification.component', <<===== from here
},
shared: {
....
}
],
};
更新
我找到了一个很好的参考:Mocking federated modules in host application for jest
并尝试了类似的方法,但我仍然得到了同样的错误。
test('dashboard component',()=>{
jest.mock('common/NotificationComponent',
() => {
,
{ virtual: true }
);
const wrapper = mount(
<Provider store={myStore}>
<Router>
<DashboardComponent />
</Router>
</Provider>
)
})
但同样的错误。怎么了?
发布于 2022-07-11 09:32:51
好吧。最后我找到了答案。
在上面的代码片段中,我做了一件错误的事情,如下所述,
在前面的尝试中,它仍然失败,因为我在it(...)
或test(...)
块中使用了如下所示的
test('dashboard component',()=>{
jest.mock('common/NotificationComponent',
() => {
myFunc: () => 'hello'
,
{ virtual: true }
);
const wrapper = mount(
<Provider store={myStore}>
<Router>
<DashboardComponent />
</Router>
</Provider>
)
})
解决方案
下面的代码,
jest.mock('common/NotificationComponent',
() => {
myFunc: () => 'hello'
,
{ virtual: true }
);
您应该将放在文件的顶部。不要把它放在it(...)
或test(...)
块中。所以它看起来像下面,
import "@testing-library/jest-dom";
import { shallow, mount } from "enzyme";
jest.mock('common/NotificationComponent',
() => {
myFunc: () => 'hello'
,
{ virtual: true }
);
test('dashboard component',()=>{
const wrapper = mount(
<Provider store={myStore}>
<Router>
<DashboardComponent />
</Router>
</Provider>
)
})
https://stackoverflow.com/questions/72909100
复制相似问题