playwright icon indicating copy to clipboard operation
playwright copied to clipboard

[Feature]: Better API for handling request interceptors

Open andreaslarssen opened this issue 1 year ago • 3 comments

🚀 Feature Request

I'm new to Playwright, coming from Cypress, so I might have missed something here. It seems to me that when intercepting API requests with the page.route() method, you're not able to specify which http method to intercept? If it's not possible, I would very much like to see that implemented

Example

I was expecting to see something like:

  await page.route('POST', 'my/route', (route) => {
      route.fulfill(
        { json },
      );
    });

Motivation

It would make it possible to write cleaner code. Am I missing something here? How are we supposed to mock two different request to same URL with different http method

andreaslarssen avatar Jan 08 '25 15:01 andreaslarssen

You can do this:

await page.route('my/route', (route, request) => {
  if (request.method() === 'POST')
    route.fulfill({ json })
  else
    route.continue();
});

Skn0tt avatar Jan 08 '25 15:01 Skn0tt

@Skn0tt Yes, and it's not exactly ideal. It leads to bloated boilerplate code. Seems like an easy fix to significantly raise developer friendliness?

andreaslarssen avatar Jan 08 '25 15:01 andreaslarssen

Also, when both intercepting a request to mock it, and waiting for the same request, you would need to do that separately? And test for method every time?

await page.route('my/route', (route, request) => {
  if (request.method() === 'POST')
    route.fulfill({ json })
  else
    route.continue();
});

page.waitForRequest(request =>   
  request.url() === 'my/route' && request.method() === 'POST', 
); 

await page.getByText('trigger request').click(); 
const request = await requestPromise;

Wouldn't it be nicer to somehow define a request and then do whatever with it?

const request = new Request('my/route', 'POST');
await request.fulfill({ json });
await page.getByText('trigger request').click(); 
await request.waitFor();

andreaslarssen avatar Jan 22 '25 15:01 andreaslarssen

Why was this issue closed?

Thank you for your involvement. This issue was closed due to limited engagement (upvotes/activity), lack of recent activity, and insufficient actionability. To maintain a manageable database, we prioritize issues based on these factors.

If you disagree with this closure, please open a new issue and reference this one. More support or clarity on its necessity may prompt a review. Your understanding and cooperation are appreciated.

pavelfeldman avatar Sep 04 '25 01:09 pavelfeldman

@pavelfeldman Could we please reopen?

andreaslarssen avatar Sep 10 '25 19:09 andreaslarssen