To create an API request interceptor that logs test names and correlation IDs in Playwright, you can use the page.route()
method along with a custom interceptor function. Here's how to do it:
First, import the fixtures
module from @playwright/test
to access the test information:
import { fixtures } from '@playwright/test';
const { testInfo } = fixtures;
Next, define your interceptor function that takes a request
parameter of type APIRequest
. Inside the function, access the test name using testInfo.title
and generate a correlation ID with your own logic. Log the test name, correlation ID, request method, and URL:
async function myInterceptor(request: APIRequest) {
const testName = testInfo.title;
const correlationId = generateCorrelationId(); // replace with your own logic
console.log(`[${testName}] [${correlationId}] Intercepted ${request.method()} ${request.url()}`);
// continue with original request
return await request.continue();
}
Finally, register your interceptor by calling page.route()
with a URL pattern and your interceptor function:
// register interceptor for all requests to api.ray.run
page.route('https://api.ray.run/*', myInterceptor);
This code registers the myInterceptor
function for all requests matching the URL pattern https://api.ray.run/*
. Now, whenever an API request is made, the interceptor logs the test name and correlation ID.
If you still have questions, please ask a question and I will try to answer it.
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].