reactjsnext.jsjestjsreact-testing-libraryapp-router

Jest test - useFormStatus is not a function


On Next.js 14 and have a simple test with useFormStatus hook. It is causing an error TypeError: (0 , _reactdom.useFormStatus) is not a function

As soon as I remove the useFormStatus, the tests pass.

Source file using useFormStatus:


import { useFormStatus } from "react-dom";

export default function MyComponent(){
    const {pending} = useFormStatus()
    if(pending){
        return null
    }
    return ( <div>some jsx</div>)

}

And the test:

it('renders', () => {
    render(<MyComponent />) //error on render
    expect(1).toBe(1)

})

Should I try to mock useFormStatus? In Next 13 I believe useFormStatus was experimental, but I believe it is now stable.


Solution

  • In Next.js 13, the useFormStatus hook was part of the react-dom package, but as of Next.js 14, it seems that it's no longer provided by react-dom.

    To resolve this issue, you have a few options:

    1. Mock the useFormStatus hook: If you're only testing MyComponent and you don't need the actual functionality of useFormStatus, mocking it could be a viable option. You can create a mock implementation for it. jest.mock('react-dom', () => ({ __esModule: true, useFormStatus: jest.fn(), })); This way, you're telling Jest to replace useFormStatus with a mock function, which should eliminate the TypeError during testing.
    2. Use a different hook or approach: If useFormStatus is crucial for your component logic and you need to test it properly, consider whether it's still available in a different package or if there's a replacement hook you can use.