To mock a server API with @playwright/test, you can access your application's REST API and send requests directly from Node.js. This is helpful for testing your server API, setting up server-side state, and validating post-conditions.
First, use APIRequestContext
methods to write an API test configuration. APIRequestContext
can send various HTTP(S) requests over the network. For instance, you can create a new repository, add issues, validate server state, and delete the repository after tests.
If your API requires authorization, configure the token using test.use()
. To reuse authentication state between contexts, use apiRequestContext.storageState()
to retrieve storage state from an authenticated context and create new contexts with that state.
Split long tests into multiple steps with test.step()
API:
import { test } from '@playwright/test';
await test.step('Log in', async () => {
// ...
});
await test.step('news feed', async () => {
// ...
});
To launch a webserver during tests, use Playwright's webServer
option in playwright.config.ts
:
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run start',
url: 'http://127.0.0.1:3000',
timeout: 120 * 1000,
},
});
Now you can effectively mock and test your server APIs using Playwright.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].