To test APIs without opening a browser page using @playwright/test, follow these steps:
Use beforeEach
and afterEach
hooks for any necessary configurations or preconditions.
Send requests from Node.js using Playwright's APIRequestContext
methods.
Establish preconditions and validate post-conditions after running actions in the browser.
Simplify your test suite by reusing authentication state across multiple tests.
Be aware of context-level requests specific to individual test cases and global-level requests that persist across all tests within a file.
Here's a TypeScript example using @playwright/test:
import { test, expect } from '@playwright/test';
test.beforeEach(async ({ context }) => {
// Set up preconditions, e.g., authenticate
await context.extend({
baseURL: 'https://ray.run/',
headers: { 'Authorization': 'Bearer your_token' },
});
});
test.afterEach(async ({ context }) => {
// Clean up after each test
});
test('API test without browser', async ({ context }) => {
// Send a request using APIRequestContext
const response = await context.request.get('/api/endpoint');
const data = await response.json();
// Validate the response
expect(response.status()).toBe(200);
expect(data).toHaveProperty('key', 'value');
});
By following these steps, you can easily test APIs using Playwright without opening a browser page.
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].