Rayrun

How do I set up and execute API tests using Playwright?

Answer

Creating API Tests with Playwright

First, you'll need to use the APIRequestContext methods in Playwright. These methods allow you to send HTTP(S) requests over the network, giving you direct access to your application's REST API. This is useful for server API testing, preparing server-side state, or validating server-side post-conditions.

Setting Up API Test Configuration

You'll need to set up your API test configuration. For instance, if you're testing GitHub's API, you'll need to configure the token. You can do this in the configuration file or in the test file with test.use(). Your configuration should include a baseURL and extraHTTPHeaders.

test.use({
  baseURL: 'https://ray.run/api',
  extraHTTPHeaders: { 'Authorization': 'Bearer your_token' }
});

Writing Tests

Next, write your tests using Playwright Test's built-in request fixture. This fixture respects your configuration options and is ready to send requests. For example, you can create new issues in a repository by sending POST requests with request.post(), and validate them with GET requests via request.get().

test('create and validate new issue', async ({ request }) => {
  const response = await request.post('/issues', { body: { title: 'New issue' } });
  const issue = await response.json();
  const validationResponse = await request.get(`/issues/${issue.id}`);
  expect(validationResponse.status()).toBe(200);
});

Validating Post-Conditions

If you need to validate post-conditions after creating new issues, you can reuse the context request by all tests within one file using test.beforeAll(). This allows you to dispose of all responses at once when you're done testing with test.afterAll().

let issueId: string;

test.beforeAll(async ({ request }) => {
  const response = await request.post('/issues', { body: { title: 'New issue' } });
  const issue = await response.json();
  issueId = issue.id;
});

test.afterAll(async ({ request }) => {
  await request.delete(`/issues/${issueId}`);
});

For more details, check out our API testing using Playwright blog post.

References

Thank you!
Was this helpful?
Still have questions?

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

Related Questions

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