Next.js Discord

Discord Forum

Testing async React Server Component using Vitest and React Test Library

Answered
Giant Angora posted this in #help-forum
Open in Discord
Avatar
Giant AngoraOP
Lets say I have a component that looks like this

const DashboardFeature = async (): Promise<JSX.Element> => {
  const myFakeResult = await new Promise((resolve) => {
    setTimeout(() => {
      resolve('I am the data');
    }, 1000);
  });

  return <div>{myFakeResult}</div>;
};

export default DashboardFeature;


I am trying to test it like this

import { render, screen } from '@testing-library/react';
import { it, expect } from 'vitest';
import DashboardFeature from './DashboardFeature';
import { Suspense } from 'react';

it('displays default welcome message when feature is disabled', async () => {
  render(
    <Suspense>
      <DashboardFeature />
    </Suspense>
  );

  expect(await screen.findByText('welcome disabled')).toBeInTheDocument();
});


When I run the test I get this error

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

Has anyone had any success doing a test like this?

I am running Next 13.5.4 and react 18
Answered by Giant Angora
Ok so I got this running. Ended up following the steps here. https://www.marcusoft.net/2022/11/nextjs-testing-async-react-components.html The main part is this
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import HeroPage from "./page";

describe("HeroPage", () => {
  it("should render the heading", async () => {
    // act
    const jsx = await HeroPage({ params: { id: 2 } });
    render(jsx);

    // assert
    const headingElement = screen.getAllByTestId("heading");
    expect(headingElement).toHaveTextContent("Luke Skywalker");
  });
});
Awaiting your component to get the JSX and then passing that to the react test libaray.
View full answer

1 Reply

Avatar
Giant AngoraOP
Ok so I got this running. Ended up following the steps here. https://www.marcusoft.net/2022/11/nextjs-testing-async-react-components.html The main part is this
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import HeroPage from "./page";

describe("HeroPage", () => {
  it("should render the heading", async () => {
    // act
    const jsx = await HeroPage({ params: { id: 2 } });
    render(jsx);

    // assert
    const headingElement = screen.getAllByTestId("heading");
    expect(headingElement).toHaveTextContent("Luke Skywalker");
  });
});
Awaiting your component to get the JSX and then passing that to the react test libaray.
Answer