Network and API
API Setup for UI Tests
API Setup for UI Tests: definition, backend test data setup, UI validation examples, mistakes, and practice.
Definition and Brief Explanation
Definition: API setup for UI tests means preparing backend state through API calls before validating the UI flow.
Explanation: Instead of using slow UI steps to create every precondition, tests can create users, orders, tokens, or records through APIs, then open the UI at the point being tested.
Why It Matters
- It makes tests faster and more controlled when backend state matters.
- It lets you test success, failure, and edge cases without depending on unstable services.
- It helps verify that the UI sends or receives the expected API traffic.
- It supports clean setup for UI tests through API calls.
How It Works
- Identify the request or API state involved in the test.
- Set up the route, request context, or response wait before the UI action.
- Trigger the UI behavior.
- Assert both the page result and important request/response details when needed.
Syntax and Examples
Example 1: Create data through API
const res = await request.post('/api/projects', { data: { name: 'Demo' } });
const project = await res.json();
await page.goto(`/projects/${project.id}`);
Explanation: API creates data, then UI validates the project page.
Common Mistakes
- Mocking so much that the test no longer checks real integration.
- Using URL patterns that match unrelated requests.
- Creating shared backend data that breaks parallel tests.
- Forgetting the UI assertion after network setup.
Interview Notes
- What problem does API Setup for UI Tests solve?
- When would you mock instead of using the real API?
- How do you avoid over-mocking?
- How do network waits differ from UI assertions?
Practice Task
Create a small Playwright example for API Setup for UI Tests. Add one positive assertion, one note about what can go wrong, and one improvement that would make the test more maintainable.