Rayrun

How do I use Playwright to test APIs without opening a browser page?

Answer

To test APIs without opening a browser page using @playwright/test, follow these steps:

1. Set up tests with hooks

Use beforeEach and afterEach hooks for any necessary configurations or preconditions.

2. Use APIRequestContext methods

Send requests from Node.js using Playwright's APIRequestContext methods.

3. Send API requests in UI tests

Establish preconditions and validate post-conditions after running actions in the browser.

4. Reuse authentication state

Simplify your test suite by reusing authentication state across multiple tests.

5. Choose between context and global requests

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.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

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].