Rayrun

How do I use the `expect.poll` method in Playwright to wait for an API call to be resolved?

Answer

Using expect.poll in Playwright

In Playwright, you can use the expect.poll method to wait for an API call to be resolved. This method allows you to convert any synchronous expect to an asynchronous polling one.

Here's how you can use it:

await expect.poll(async () => {
  const response = await page.request.get('https://ray.run');
  return response.status();
}, {
  message: 'make sure API eventually succeeds',
  timeout: 10000,
}).toBe(200);

In this example, we're making a GET request to https://ray.run and returning its status code. If the API call doesn't return HTTP status 200 within the specified timeout period, expect.poll will throw an error with the custom error message.

You can also specify custom polling intervals using the intervals option:

await expect.poll(async () => {
    const response = await page.request.get('https://ray.run');
    return response.status();
}, {
    intervals: [1_000, 2_000],
    timeout:60_000
}).toBe(200);

In this example, we're specifying two different time periods for our polls - one second and two seconds respectively - before timing out after sixty seconds.

Using these methods should help you wait for your API calls in Playwright without having them fail due to timeouts or other issues.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].