apiSpy Fixture
The apiSpy fixture provides access to captured API requests and responses within your tests.
Usage
import { testWithApiSpy as test, expect } from 'playwright-api-spy';
test('example', async ({ request, apiSpy }) => {
await request.get('/users');
console.log(apiSpy.lastRequest);
console.log(apiSpy.lastResponse);
});
Properties
requests
Array of all captured requests.
entries
Array of all captured entries (request + response pairs).
lastRequest
Most recently captured request.
lastResponse
Most recently captured response.
expect(apiSpy.lastResponse?.status).toBe(200);
expect(apiSpy.lastResponse?.duration).toBeLessThan(1000);
lastEntry
Most recently captured entry (request + response).
isPaused
Whether capturing is currently paused.
Methods
addContext(context: string)
Add context annotation to subsequent requests.
apiSpy.addContext('Creating test user');
await request.post('/users', { data: { name: 'Test' } });
apiSpy.clearContext();
clearContext()
Clear the context annotation.
pause()
Pause request capturing.
resume()
Resume request capturing.
clear()
Clear all captured requests.
Hooks
onRequest(callback)
Called when a request is made.
onResponse(callback)
Called when a response is received.
apiSpy.onResponse((req, res) => {
if (res.duration > 1000) {
console.warn(`Slow: ${req.path} took ${res.duration}ms`);
}
});
onError(callback)
Called when a request fails.