2

I have problems about testing component that it's used dynamic import in nextjs 12. I show up some info about technical:

  • NextJS 12 use SWC (not use babel)
  • React 18
  • Jest + React testing library

Here example: Component:

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>
....

File test:

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();
  });
});

And I get error:

 <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.

I tried with solution (How to unit test Next.js dynamic components?) but i don't want to use babel because app would be run failed.

san
  • 1,515
  • 11
  • 18

1 Answers1

0

Assuming you are rendering <Hello /> within your Home component, try updating your test to use async/await, and use findByText instead of 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();
  });
});

React Testing Library docs about async/await:

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

Ethan Ryan
  • 467
  • 10
  • 16