Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jest with Async Server Components

I'm trying to test a React Server Component, which returns a Promise. The standard render method in Jest doesn't like that.

I checked the similar questions, but all are > 4 years old and deal with componentDidMount etc.

/// Home.tsx
async function Home(props: Props) : Promise<JSX.Element> {
 // call async functions to setup component
}

/// home.test.ts
describe('Home', () => {
  it('renders a heading', () => {
     render(<Home />);
  }
}

Error:

'Home' can not be used as a JSX element

Any suggestions on how to work around this? An obvious solution is to make the component not return a Promise, but than I'm writing code to satisfy the test framework which is not ideal.

like image 898
Paul van Brenk Avatar asked May 31 '26 10:05

Paul van Brenk


1 Answers

Happened upon this while looking through the bounties. I am not sure what all you have tried but I may be able to help. Obviously you know that Jest's can't return a Promise. However there may be a workaround by using act from test-utils. Try something like this

import { render } from '@testing-library/react';
import { act } from 'react-dom/test-utils';

describe('Home', () => {
  it('renders a heading', async () => {
    await act(async () => {
      render(await Home());
    });
  });
});
like image 133
dmkehl Avatar answered Jun 01 '26 22:06

dmkehl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!