waitFor chạy lại callback theo chu kỳ (mặc định 50ms) cho tới khi không ném lỗi, hoặc hết timeout (mặc định 1000ms). Ba lỗi hay gặp:
1. Nhồi nhiều assertion vào một waitFor. Assertion đầu fail thì các assertion sau không chạy; khi test fail bạn chỉ thấy lỗi đầu tiên và mất tới 1s mỗi lần retry.
// avoid
await waitFor(() => {
expect(screen.getByText("Saved")).toBeInTheDocument()
expect(onSave).toHaveBeenCalledTimes(1)
})
// prefer: wait for one thing, then assert the rest synchronously
expect(await screen.findByText("Saved")).toBeInTheDocument()
expect(onSave).toHaveBeenCalledTimes(1)2. Đặt side effect trong callback. Callback bị gọi nhiều lần, nên await user.click(...) hay fireEvent nằm trong waitFor sẽ chạy lặp lại.
3. Dùng waitFor với assertion phủ định. await waitFor(() => expect(screen.queryByText("x")).toBeNull()) pass ngay lập tức nếu element chưa kịp xuất hiện. Muốn chờ nó biến mất thì dùng waitForElementToBeRemoved(element) — hàm này bắt buộc element phải tồn tại lúc đầu, nếu không nó ném lỗi.
Chọn API:
- Chờ element xuất hiện → findBy* (đã là waitFor + getBy).
- Chờ element biến mất → waitForElementToBeRemoved.
- Chờ thứ không phải DOM (mock được gọi, URL đổi) → waitFor với đúng một assertion.