Rayrun
โ† Back to Discord Forum

Error: route.fetch: Browser has been closed

Hello, I am doing a PW Udemy course and there is example of using route.fetch to manipulate an API response.

It works only while using the debug mode or when using page.pause() before the expected interfered response is expected.

I found the solution to this problem here: https://github.com/microsoft/playwright/discussions/12810

The problem is that without explicitly adding await page.waitForResponse(url);

I got an error: Error: route.fetch: Browser has been closed

This code causes the mentioned error:

await page.route(
    /api\/ecom\/order\/get-orders-for-customer\/.*/,
    async (route) => {
      const body = JSON.stringify({ data: [], message: "No Orders" });
      const response = await route.fetch(); // -> Error: route.fetch: Browser has been closed

      await route.fulfill({
        response,
        body,
      });
    }
  );
  await ordersMenuButton.click();

After adding the explicit waitForResponse it works fine:

await page.route(
    /api\/ecom\/order\/get-orders-for-customer\/.*/,
    async (route) => {
      const body = JSON.stringify({ data: [], message: "No Orders" });
      const response = await route.fetch();

      await route.fulfill({
        response,
        body,
      });
    }
  );
  await ordersMenuButton.click();
  await page.waitForResponse(/api\/ecom\/order\/get-orders-for-customer\/.*/);

I think it should be mentioned in the documentation here: https://playwright.dev/docs/api/class-route#route-fetch

Or I don't understand this concept and it is obvious but my lack of experience with PW doesn't allow me to notice it if so could someone explain it to me?

This thread is trying to answer question "Why does the error `Error: route.fetch: Browser has been closed` occur when using `route.fetch` and how can it be resolved?"

1 reply

When I execute it using npx I got: Error: route.fetch: Request context disposed. I also noticed that I don't need to use waitForResponse also adding some assertion that is fullfilled by the changed response works fine, for example:

await page.route(
    /api\/ecom\/order\/get-orders-for-customer\/.*/,
    async (route) => {
      const body = JSON.stringify({ data: [], message: "No Orders" });
      const response = await route.fetch();

      await route.fulfill({
        response,
        body,
      });
    }
  );
  await ordersMenuButton.click();
  await expect(page.getByText("Please Visit Back Us")).toHaveCount(1)

So now it makes sense, I think it answers my question ๐Ÿ˜„

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