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

No comments:

Post a Comment