user19448827
user19448827

Reputation: 245

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.

Upvotes: 2

Views: 765

Answers (2)

Pedro Corado
Pedro Corado

Reputation: 39

I was able to make it work at this way:

jest.mock("react-dom", () => ({
  ...jest.requireActual("react-dom"),
  useFormStatus: jest.fn(() => ({
    pending: false,
  })),
}));

The main issue with the approach in the main thread comment is that the entire react-dom lib was being overwritten and the test fails when jest and react tries to use its other methods.

Upvotes: 0

Kira Dresst
Kira Dresst

Reputation: 52

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.

Upvotes: 1

Related Questions