How to write jest unit test for NextJs layout which includes server component

24 views Asked by At

I wrote a nextjs layout component like this

export default function RootLayout({
    children
}: {
    children: React.ReactNode
}) {
    return (
        <html lang="en">
            <body>
                <NextAuthProvider>
                    <Header />
                    {children}
                </NextAuthProvider>
            </body>
        </html>
    )
}
const Header = async () => {
    const session = await getServerSession(authOptions)
    return ...
}

The problem is is an async server component. Seems like jest can't handle it, it show error when I try to run

Error: Uncaught [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.]

What should I do?

Tried to write unit test for it use Jest and testing-library

describe("RootLayout", () => {
    it("should render correct", async () => {
        const { getByText } = render(
            <RootLayout>
                <div>Test</div>
            </RootLayout>
        )

        expect(getByText("Test")).toBeInTheDocument()
    })
})

I also try async/await render but it doesn't work unless remove async from Header component

describe("RootLayout", () => {
    it("should render correct", async () => {
        const jsx = await RootLayout({ children: <div>Test</div> })
        const { getByText } = render(jsx)

        expect(getByText("Test")).toBeInTheDocument()
    })
})
0

There are 0 answers