Sunday, October 12, 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

Test APIs in Playwright (API in E2E test)

 Perform following steps,

  1. Import {APIRequestContext} from '@playwright/test'
  2. Declare a variable to get the API context
    • let apiContext: APIRequestContext;
  3. User before all to initialize the API context
    • test.beforeAll (async ({ playwright } )=> { 

      apiContext = await playwright.request.newContext({ 

      baseURL: 'api.base.URL', 

      extraHTTPHeaders: { 

      'Accept': 'application/json', 

      'Content-Type': 'application/json', 

      }) 

      })

  4. Destroy the context after all
    • test.afterAll ( async ({ }) => { 

      await apiContext.dispose(); 

      })

  5. Make request in test as required
    • await apiContext.post('URL', {data: payLoad})

Friday, October 10, 2025

Test APIs in Playwright (with E2E tests)

 Perform following steps,

  1. In playwright.cofig.ts, create a project
    • Provide test name:
    • Provide testDir:
    • In use:
      • Provide baseURL:
      • Provide extraHTTPHeaders:
        • 'Accept':
        • 'Content-Type':
  2. In test, call back request instead of page
  3. In request.METHOD('URL')
    • request.get('URL')
    • request.post('URL', {body})
  4. Get the response in a variable
    • const response = request.get('/products')
    • For status, response.status()
    • For header, response.headers()
    • For body, response.body()
    • For JSON, response.json()
    • Also others availble
  5. For assertions, use expect
    • For status, expect(response.status()).toBe(200)
    • For header content type match
      • expect(response.headers()['conten-type']).toContain('application/json')
  6. Get the response body in a variable
    • const responseBody = response.json()
  7. For assertions in the body
    • expect(responseBody).toHaveProperty('success', true)
    • expect(responseBody).toHaveProperty('data')
    • expect(Array.isArray(responseBody.data)).toBe(true)
  8. Run test project-wise, run with the following command
    • npx playwright test --project project_name_given_playwright.config