Skip to content

An update to Transitioner inside a test was not wrapped in act(...) #9414

@kimsagro1

Description

@kimsagro1

Describe the bug

I'm using tanstack router and have a route that throws a redirect

import { createFileRoute, redirect } from '@tanstack/react-router';

export const Route = createFileRoute('/restricted')({
  beforeLoad: () => {
    throw redirect({ to: '/' });
  },
  component: RouteComponent,
});

function RouteComponent() {
  return <div>Hello "/restricted"!</div>;
}

And then testing that the redirect occurs using vitest browser mode

test('restricted page redirects', async () => {
  const { router } = await renderRoute('/restricted');
  expect(router.history.location.pathname).toBe('/');
});

async function renderRoute(path: keyof FileRoutesByFullPath) {
  const memoryHistory = createMemoryHistory({
    initialEntries: [path],
  });

  const router = createRouter({
    routeTree,
    defaultPreloadStaleTime: 0,
    defaultPendingMinMs: 0,
    history: memoryHistory,
  });

  const result = await render(<RouterProvider router={router} />);

  return {
    ...result,
    router,
  };
}

The test succeeds but logs the following to the console

An update to Transitioner inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act

This only happens when the route throws a redirect, if I test another route without the redirect, then the test passes without any console logs

test('about page renders', async () => {
  await renderRoute('/about');
  await expect.element(page.getByText('Hello from About!')).toBeVisible();
});

I have also tried wrapping the test codes in an act and various combination of wrapping the code in waitUntil etc, but without success.

I'm unsure whether the issue lie with tanstack router or vitest

I have included a stackblitz that reproduced the issue, you will see the logs in the terminal

Reproduction

https://stackblitz.com/edit/vitejs-vite-o3senmym

System Info

System:
  OS: Linux 5.0 undefined
  CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
  Memory: 0 Bytes / 0 Bytes
  Shell: 1.0 - /bin/jsh
Binaries:
  Node: 20.19.1 - /usr/local/bin/node
  Yarn: 1.22.19 - /usr/local/bin/yarn
  npm: 10.8.2 - /usr/local/bin/npm
  pnpm: 8.15.6 - /usr/local/bin/pnpm
npmPackages:
  @vitejs/plugin-react: ^5.1.2 => 5.1.2 
  @vitest/browser-preview: ^4.0.16 => 4.0.16 
  vite: ^7.2.7 => 7.3.0 
  vitest-browser-react: ^2.0.2 => 2.0.2

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions