开发者问题收集

在 nextjs 12 中使用 JEST 和 React 测试库进行动态导入失败,使用 SWC(不使用 babel)

2023-03-17
1290

我在测试 nextjs 12 中使用动态导入的组件时遇到问题。 我展示了一些技术信息:

  • NextJS 12 使用 SWC(不使用 babel)
  • React 18
  • Jest + React 测试库

这里是示例: 组件:

import styles from '@/pages/index.module.css';
import dynamic from 'next/dynamic';
const Hello = dynamic(() => import('../components/Hello'));

export default function Home() {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
....

文件测试:

import { render, screen } from '@testing-library/react';
import Home from '@/pages/index';

describe('Home', () => {
  it('renders a heading', () => {
    render(<Home />);

    const heading = screen.getByRole('heading', {
      name: /welcome to next\.js!/i,
    });

    expect(heading).toBeInTheDocument();
    expect(screen.getByText('Hello')).toBeInTheDocument();
  });
});

出现错误:

 <DsPropertyContent/> test › normal work correctly

    Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

我尝试了解决方案( 如何对 Next.js 动态组件进行单元测试? )但我不想使用 babel,因为应用程序会运行失败。

1个回答

假设您正在 Home 组件中渲染 <Hello /> ,请尝试更新您的测试以使用 async/await ,并使用 findByText 而不是 getByText

describe('Home', () => {
  it('renders a heading', async () => {
    render(<Home />);

    const heading = screen.getByRole('heading', {
      name: /welcome to next\.js!/i,
    });

    expect(heading).toBeInTheDocument();
    expect(await screen.findByText('Hello')).toBeInTheDocument();
  });
});

有关 async/await 的 React Testing Library 文档:

https://testing-library.com/docs/dom-testing-library/api-async/

Ethan Ryan
2023-05-10