testing-library/react-testing-library

React.act is not a function in vitest

Closed this issue · 2 comments

Here is my test code:

// @vitest-environment jsdom

import { useChatSessionFocus } from './useChatSessionFocus';
import { act, renderHook } from '@testing-library/react';
import { expect, it } from 'vitest';

it('focusMessages changes the focused component to messages', () => {
  const { result } = renderHook(() => useChatSessionFocus(true));

  expect(result.current.focusedComponent).toBe('message-form');

  act(() => {
    result.current.focusMessages();
  });

  expect(result.current.focusedComponent).toBe('messages');
});

It is failing in CI with:

   × returns the expected initial state 10ms
     → React.act is not a function

There is also a warning:

`ReactDOMTestUtils.act` is deprecated in favor of `React.act`. Import `act` from `react` instead of `react-dom/test-utils`. See https://react.dev/warnings/react-dom-test-utils for more info.

The confusing part is that the exact same test setup works perfectly fine locally.

I cannot figure out why vitest or react-testing-library is behaving differently in CI.

I already considered the possibility of version mismatch, but adding overrides didn't help:

"overrides": {
  "zod": "3.24.2",
  "react": "19.1.0",
  "react-dom": "19.1.0"
},

Would appreciate any guidance.

Can you please share what version of RTL do you have installed?

Turns out this was because of NODE_ENV='production'