1、[React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.
原因是:没有正确地设置IntlProvider导致的。
解决方案:
使用UmiJs提供的IntlProvider组件来提供intl对象,用IntlProvider组件包裹,同时使用jest.mock模拟国际化语言,以及使用messages属性映射菜单项国际化文案。
/** 每个测试用例运行前先运行模拟国际化语言 */
beforeEach(() => {
jest.mock('@/hooks/useLocale', () => {
// mockImplementation指定mock函数的具体实现
return jest.fn().mockImplementation(() => ({
getMessage: jest.fn((id) => id),
}));
});
});
/** 路由映射 */
const messages = {
'menu.dashboard': 'Dashboard',
'menu.resource': 'Resource',
'menu.document': 'Document',
'menu.downloadedresource': 'DownloadedResource',
};
/** 正确渲染菜单 */
test('should render menu correctly', async () => {
const props = {
headerView: {
route: {
routes: [
{
name: 'dashboard',
path: '/',
},
{
name: 'resource',
path: '/resource',
children: [
{
name: 'document',
path: '/resource/document',
},
{
name: 'downloadedresource',
path: '/resource/downloadedresource',
},
],
},
],
},
location: {
pathname: '/',
},
},
};
render(
/**
* 使用IntlProvider组件来提供intl对象
* 将 locale 属性设置为 "en-US",并使用messages属性来提供国际化文本,
* 其目的是传递给IntlProvider组件,确保所有国际化文本都能被正确渲染,以便在用例中使用英文翻译
*/
<IntlProvider locale="en-US" messages={messages}>
<MenuRender {...props} />
</IntlProvider>,
);
await waitFor(() => screen.getByText('Dashboard'));
expect(screen.getByText('Dashboard')).toBeInTheDocument();
expect(screen.getByText('Resource')).toBeInTheDocument();
expect(screen.getByText('Document')).toBeInTheDocument();
expect(screen.getByText('DownloadedResource')).toBeInTheDocument();
});
2、自定义的class类名为空,如果你是用CSS Module实现CSS的话,可以用以下方法解决。
class为空时:
采用的解决方案是:使用 identity-obj-proxy 插件。
(1)先下载 identity-obj-proxy 插件;
yarn add identity-obj-proxy
(2)然后在 jest.config.js 文件下设置,class的值就会出现了。
module.exports = {
moduleNameMapper: {
'\\.(css|less)$': 'identity-obj-proxy',
},
};
3、TypeError: Cannot read properties of undefined (reading '@@initialState')
原因是:是因为测试环境没有提供正确的 initialState 值。
解决方案:
使用 jest.mock 来模拟 useModel 钩子返回 initialState 和 setInitialState 函数
jest.mock('umi', () => ({
useModel: () => ({
initialState: {
currentUser: {
accountName: 'John Doe',
avatar: 'avatar.jpg',
},
},
setInitialState: jest.fn(),
}),
}));
test('AvatarDropdown', () => {
render(<AvatarDropdown />);
});