Sunday, October 12, 2025

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})

No comments:

Post a Comment