Skip to content

Testing Asynchronous State Update in React Component not possible #6031

Closed Answered by Muhamedkaric
Muhamedkaric asked this question in Q&A
Discussion options

You must be logged in to vote

Solution is to use it like this:

beforeEach(() => {
    vi.useFakeTimers();
  });

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

  test('should type in input and handle timeout', async () => {
    render(<DummyComponent />);
    const inputElement = screen.getByTestId('inputid') as any;
    fireEvent.change(inputElement, { target: { value: 'Test' } });
    vi.runAllTimers();
    vi.useRealTimers();
    const updatedElement = await screen.findByText('Test');
    expect(updatedElement).toBeInTheDocument();
  });

key points:

  • beforeEach use fake timers
  • before doing screen.findBy.... use again real timers or it will stuck forever
  • when using screen.findBy you don't need things above being…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Muhamedkaric
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
1 participant
Converted from issue

This discussion was converted from issue #6028 on July 03, 2024 14:36.