Skip to content

waitFor not working when vi.useFakeTimers is used #565

@jonaskuske

Description

@jonaskuske

When vi.useFakeTimers is used in a test, waitFor does not longer run change detection.

it('works', async () => {
  vi.useFakeTimers()
  const view = await render(MyComponent)
  view.detectChanges()
  expect(screen.getByRole('input').toHaveAccessibleDescription(/something/))
})

it('does not work', async () => {
  vi.useFakeTimers()
  await render(MyComponent)
  await waitFor(() => expect(screen.getByRole('input').toHaveAccessibleDescription(/something/)))
})

It only happens when using Vitest, not when using Jest. (in fact, globalThis.jest = vi in the setup script suffices as workaround for some reason)

The cause appears to be the use of setTimeout in the waitForWrapper: https://github.com/testing-library/angular-testing-library/blob/main/projects/testing-library/src/lib/testing-library.ts#L592

The problem disappears when I replace

    setTimeout(() => detectChanges(), 0);

with

    Promise.resolve().then(() => detectChanges());

I assume that waitFor itself is using the fake setTimeout and thus never runs, waiting for the time to advance.

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