Skip to content

How to use waitFor correctly #1247

@KylinLee

Description

@KylinLee

I'm using @testing-library/react and jest to test my library, I followed the docs, throw an error in waitFor's callback function, but the test case will fail due to the callback throw error, code like this:

import { render, fireEvent, waitFor } from '@testing-library/react'

const { container } = render(<Root />)

const querySelector = (selector: string): Element => {
  const el = container.querySelector(selector)
  expect(el).not.toBeNull()
  return el
}

fireEvent(_, _)

await waitFor(() => querySelector(_), {
  container,
  interval: 100,
  timeout: 500
})

// or throw a custom error, test case also fail
await waitFor(() => {
  if( !container.querySelector(_) ){
    throw new error()
  }
}, {
  container,
  interval: 100,
  timeout: 500
})

when I running test:

 expect(received).not.toBeNull()

 Received: null

I wish the callback execute every 100ms for 500ms if element not found, how to achieve this, thanks for your answer.

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