Skip to content

Query never updates when using Vitest fake timers #6994

@dyst5422

Description

@dyst5422

Describe the bug

When using fake timers with vitest, the query result never updates.

import { it, expect, afterAll, beforeAll, vitest } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';

beforeAll(() => {
  vitest.useFakeTimers();
});

afterAll(() => {
  vitest.useRealTimers();
});

it('should work', async () => {
  const wrapper = ({ children }) => <QueryClientProvider client={new QueryClient()}>{children}</QueryClientProvider>;
  const { result } = renderHook(
    () => {
      const query = useQuery({
        queryKey: ['some'],
        queryFn: () => 'some',
      });

      console.log(query.data);

      return query;
    },
    { wrapper },
  );

  await waitFor(() => expect(result.current.data).toBe('some'));
});
stdout | src/test.spec.tsx > should work
undefined

 ❯ src/test.spec.tsx (1) 5018ms
   × should work 5016ms

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/test.spec.tsx > should work
Error: Test timed out in 5000ms.
If this is a long-running test, pass a timeout value as the last argument or configure it globally with "testTimeout".
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯

 Test Files  1 failed (1)
      Tests  1 failed (1)
   Start at  14:56:56
   Duration  5.19s

Your minimal, reproducible example

https://stackblitz.com/edit/stackblitz-starters-kwfghb?file=vite.config.ts

Steps to reproduce

run vitest on the linked example

Expected behavior

I would expect that fake timers don't block the update from propagating.

Notable, without fake timers, it works fine.

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

macOS and nodejs

Tanstack Query adapter

react-query

TanStack Query version

4 and 5

TypeScript version

5

Additional context

I was surprised as I ran into this when migrating from jest to vitest. I know Vitest uses sinonjs timers, so perhaps there's some kind of compatibility problem there.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions