ThisCalculator

Everyday

Combine Playwright API & UI Testing in One Workflow

Updated · Standard formula, shown below

This guide shows you how to combine Playwright’s API testing and UI testing into a single, reliable workflow. You’ll learn how to use API calls to set up test data, perform UI actions, and verify results—all within one test script. This approach reduces flakiness, speeds up execution, and makes your test suite more maintainable.

What You’ll Need

  • Node.js (version 16 or later) installed
  • A Playwright test project set up (or you can create one following the steps below)
  • Basic knowledge of JavaScript/TypeScript and Playwright’s test runner
  • Access to the API endpoints of the application you’re testing (or a mock server)

Step-by-Step

  1. Set up your Playwright project
    If you don’t have one, create a new directory and run npm init playwright@latest. Choose your preferred language (JavaScript or TypeScript) and test folder. This creates the basic config and example tests.
  2. Configure the base URL for API calls
    In playwright.config.ts, set use.baseURL to your application’s root URL. This allows you to use relative paths in both API requests and page navigations. For example: use: { baseURL: 'https://example.com' }.
  3. Create a test that uses API to set up data
    Use request fixture (available in Playwright test) to make API calls before UI actions. For instance, to create a user via API:
    test('create user via API then login via UI', async ({ request, page }) => {
      const response = await request.post('/api/users', {
        data: { name: 'Test User', email: 'test@example.com', password: 'secret' }
      });
      expect(response.ok()).toBeTruthy();
      // Now use the UI to login
      await page.goto('/login');
      // ... fill in credentials and submit
    });
  4. Use API responses to drive UI assertions
    Capture data from API responses and use it to verify UI content. For example, after creating a user, the API returns an ID. Use that ID to check that the UI shows the correct user profile.
  5. Clean up test data via API in afterEach or afterAll
    To keep tests isolated, delete any data created during the test using API calls in an afterEach hook. For example:
    test.afterEach(async ({ request }) => {
      await request.delete('/api/users/' + userId);
    });
  6. Combine API assertions with UI actions in the same test
    You can make an API call to verify a backend state after a UI action. For instance, after submitting a form, check via API that the data was saved correctly.
  7. Use API to bypass slow UI flows
    For scenarios like login, performing the login via API (getting a token) and then setting it in the browser context can speed up tests significantly. Use context.addCookies() or page.addInitScript to set the token.
  8. Run tests in parallel with isolated contexts
    Playwright’s default parallel execution works well with this approach because each test gets a fresh browser context and can use API to create its own data. Ensure your API calls are independent to avoid conflicts.

Common Mistakes

  • Hardcoding data – Don’t use the same user or data across tests; it leads to conflicts. Always create unique data via API.
  • Not cleaning up – Leaving test data behind can cause failures in later runs. Always delete data in hooks.
  • Mixing API and UI assertions without synchronization – If you make an API call and then immediately check the UI, the UI might not have updated yet. Use expect with retry (e.g., await expect(page.locator(...)).toHaveText(...)) or wait for network idle.
  • Using absolute URLs – When using baseURL, always use relative paths in both API and page calls to avoid hardcoding environments.
  • Ignoring response status – Always assert on the API response status (e.g., expect(response.ok()).toBeTruthy()) to catch failures early.

Tips

  • Use environment variables for API tokens, base URLs, and other sensitive data. Playwright supports .env files.
  • Create helper functions for common API operations (e.g., createUser(), deleteUser()) to avoid repetition.
  • Leverage Playwright’s request fixture – it’s automatically tied to the test’s context and can be used in hooks.
  • Use API to verify state after UI actions – this is more reliable than waiting for UI elements that may not appear.
  • Run tests in CI with a clean database – if possible, reset the database before each run to ensure a clean slate.

Troubleshooting

  • API calls fail with CORS errors – When running in the browser context, API calls from the test (using request) are made from Node.js, not the browser, so CORS doesn’t apply. If you’re using page.request (browser context), ensure the server allows CORS or use the Node.js request fixture.
  • UI doesn’t reflect API changes – The page might be cached. Use page.reload() or navigate to a fresh page after API calls. Also, ensure you’re waiting for the correct network response.
  • Tests are flaky due to timing – Use Playwright’s auto-waiting features. Avoid fixed sleeps; instead, use expect with retry or page.waitForResponse() to wait for specific API calls.
  • Data conflicts between parallel tests – Ensure each test creates unique data (e.g., using a timestamp or random string). Also, consider running tests in a single worker if conflicts are unavoidable.
  • Authentication token not working – If you’re setting a token via addCookies, make sure the cookie name and domain match what the app expects. Check the browser’s developer tools for the actual cookie.

Frequently Asked Questions

  1. Can I use API calls inside UI test steps? – Yes, you can use the request fixture anywhere in a test, including inside steps. It’s just a JavaScript object.
  2. Should I use API for all test setup? – Not necessarily. For simple UI tests, using the UI to set up data might be acceptable. But for complex scenarios (like creating multiple entities), API is faster and more reliable.
  3. How do I handle API authentication in tests? – You can obtain a token via API and then set it as a cookie or header for subsequent requests. For UI tests, you can also inject the token into the browser context.
  4. What if my API is not stable? – If the API is flaky, your tests will be too. Consider mocking the API with Playwright’s page.route() for UI-only tests, or use a test environment with a stable API.
  5. Can I run API tests without a browser? – Yes, Playwright allows you to run tests without launching a browser by using the request fixture in a test that doesn’t use the page fixture. This can speed up simple API tests.
  6. How do I debug API calls in tests? – Use console.log to print the request and response objects, or use Playwright’s trace viewer to inspect both API and UI interactions.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.