Tuesday, October 7, 2025

Test APIs in Playwright (Mock & Block)

 Perform following steps,

  1. Add the request listener at the very top (before going to the page)
    • page.on('request',request => {console.log(request.method(), request.url()) })
    • This step is to find out requests in the page
    • Similar to network tab in web developer tool of the browser
  2. Keep the page alive untill all requests are done
    • page.waitForLoadState('networkidle')
    • This step to see all requests in the page
    • Similar to network tab in web developer tool of the browser
  3. Need route function to mock it
    • page.route('requestURL', (route) => {

route.fulfill({     // fulfill to mock data, usually GET

status: 200,    // this is the status code the API will get

contentType: 'application/json',    // should be similar as it expected

body: JSON.stringify(mock_json_data_object)

}) 

})

    • Usefull for negative test cases
    • Usefull for testing micro-services
      4. Need route function to block it
    • page.route('**/*', (route) => { //URL is regular expression to match all

if (route.request().resourceType() === 'image'){    //request for images

return route.abort()}  //aborting image requests

return route.continue()    // continue if not image request

}) 

})

    • Usefull to speed up test process