前端单元测试遇到的坑

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 钩子返回 initialStatesetInitialState 函数

jest.mock('umi', () => ({
  useModel: () => ({
    initialState: {
      currentUser: {
        accountName: 'John Doe',
        avatar: 'avatar.jpg',
      },
    },
    setInitialState: jest.fn(),
  }),
}));

test('AvatarDropdown', () => {
  render(<AvatarDropdown />);
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值