Rayrun

How can I use Playwright to test server-side state and validate server-side post-conditions?

Answer

Testing API Calls with Playwright

You can use Playwright to test API calls by accessing your application's REST API. This is useful for testing your server API, preparing server-side state before visiting the web application in a test, and validating server-side post-conditions after running some actions in the browser.

Setting Up Authorization and BaseURL

GitHub API requires authorization. You can configure the token once for all tests. Also, set the baseURL to simplify the tests. You can do this in the configuration file or in the test file with test.use().

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

Creating Tests

Playwright Test comes with built-in request fixtures. You can add tests that will create new issues in the repository using request.post().

test('create issue', async ({ request }) => {
  const response = await request.post('/repos/user/repo/issues', {
    json: { title: 'New issue', body: 'Hello, world!' },
  });
  expect(response.status()).toBe(201);
});

Reusing Signed-In State

You can reuse the signed-in state in your tests with global setup. This way, you only log in once and then skip logging into each individual test.

import { test } from '@playwright/test';

test.use({
  storageState: 'storageState.json',
});

Working with Databases

If you're working with databases, test against staging environments. This ensures the data doesn't change during testing.

Writing End-to-End Tests

Use Playwright's built-in locators to find elements on web pages. These locators come with auto-waiting and retry-ability features.

const submitButton = page.getByRole('button', { name: 'submit' });

For more information, check out API testing using Playwright on our blog.

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 luc@ray.run.