Rayrun
← Back to Discord Forum

Is there a way I can add a delay to the response of a direct api request

Hi everyone,

In my test, I'm hitting the api directly for example:

const response = await request.post('/endpoint')

I'm expecting a specific status in the response body but there is a slight delay in that. Is there a way I can add a delay to the response. Or make the call again until I get the expected status in my test.

Many thanks

This thread is trying to answer question "Is there a way I can add a delay to the response of a direct api request or make the call again until I get the expected status in my test?"

4 replies

If you want to repeatedly call the endpoint until a specific status is returned, you can use a loop. With a specified amount of retries

And a timeout

If u just want delay for specific time await new Promise(resolve => setTimeout(resolve, 1000));

Or if you really want retries for given code block check the toPass https://playwright.dev/docs/test-assertions#expecttopass

Answer

Sure, you can add a delay to an API response or retry the call until you get the expected status. Here's how you can do it with Playwright.

First, wrap your API request inside an expect block and specify custom timeout and intervals. Here's an example:

await expect(async () => {
  const response = await page.request.get('https://api.ray.run');
  expect(response.status()).toBe(200);
}).toPass({
  intervals: [1000, 2000, 10000], // Retry after 1s, 2s, and then every 10s
  timeout: 60000 // Maximum timeout for retries (60 seconds)
});

In this example, the API request will be retried at specified intervals until it either passes or reaches the maximum timeout. The intervals array defines how long to wait between each retry attempt.

Feel free to customize these values according to your needs. For example, you might want shorter or longer intervals between retries or a different maximum timeout duration.

This approach ensures that your test waits for the expected status in the API response before proceeding. If the expected status is not received within the specified timeout period, an assertion error will be thrown.

For more details, check out Playwright's documentation on network requests and test assertions. Also, you might find this blog post on Exploring the Various Retry APIs of Playwright for Robust Testing helpful.

Related Discord Threads

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].