In this blog, we will dive straight into setting up a project for API testing using Playwright, focusing on the reqres API. I will guide you through each step, ensuring you have a smooth start to your API testing journey with Playwright. Let's get started!
Before we jump into the setup, let's briefly understand what Playwright is. Playwright is a Node.js library that allows you to automate Chromium, Firefox, and WebKit browsers. But it's not just limited to UI testing; you can also perform API testing with it, which is what we will focus on in this guide.
These features are made possible through the use of APIRequestContext
methods, making your API testing process smooth and efficient.
Setting up a new project is a straightforward process. Here's how to set up your Playwright project:
First, create a new project directory named playwright-api
with these commands:
mkdir playwright-api
cd playwright-api
Next, initialize the project with the following command:
npm init playwright@latest
During the initialization, there are several options to choose from. Here are the recommended choices:
tests
directory.Before we start writing tests, we need to configure our project for API testing. Replace the content of playwright.config.ts
with the following configuration to set up the base URL and necessary headers:
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: 'https://reqres.in',
extraHTTPHeaders: {
'Accept': 'application/json',
},
}
});
Playwright Test comes with a built-in request
fixture that understands the configuration options we specified above. We will use that and write our first API test.
Create a new file under the tests/
directory named basic.spec.ts
where we will add our tests.
Let's start with a simple GET request to retrieve a list of users. Here's how you can do it:
import { test, expect } from '@playwright/test';
test('has title', async ({ request }) => {
const response = await request.get('/api/users?page=2');
expect(response.ok()).toBeTruthy();
const users = await response.json();
expect(users.data.length).toBeGreaterThan(0);
});
In the above script:
expect
to assert that the response is okay and the user list is not empty.Next, let's write a test to create a new user using a POST request. Here's how:
test('Create a new user', async ({ request }) => {
const newUser = {
name: "Luffy",
job: "Pirate"
};
const response = await request.post('/api/users', { data: newUser });
expect(response.ok()).toBeTruthy();
const user = await response.json();
expect(user.name).toBe('Luffy');
});
In this script:
Now, let's quickly go over how you can write tests for PUT and DELETE requests:
To update a user's details, you can use a PUT request. Here's a simple example:
test('Update a user', async ({ request }) => {
const updatedUser = {
name: "Monkey D. Luffy",
job: "Pirate King"
};
const response = await request.put('/api/users/2', { data: updatedUser });
expect(response.ok()).toBeTruthy();
const user = await response.json();
expect(user.name).toBe('Monkey D. Luffy');
});
To remove a user, you can use a DELETE request. Here's how you can do it:
test('Delete a user', async ({ request }) => {
const response = await request.delete('/api/users/2');
expect(response.ok()).toBeTruthy();
});
While developing your API automation framework, it's common to encounter scenarios where the same action needs to be tested with various parameters. This is where data-driven testing with Playwright comes into play. It allows you to expand the scope of your tests without adding extra code, making your testing process more efficient and comprehensive.
To implement data-driven testing in Playwright, you can use an array of objects to store the different sets of data and then use a loop to iterate over the data and run the test with each set of values. Here's a step-by-step guide:
Preparing the Test Data
First, prepare an array of objects containing the different sets of data that you want to use in your tests. Here's an example:
const testData = [
{ name: 'Luffy', job: 'Pirate' },
{ name: 'Zoro', job: 'Swordsman' },
{ name: 'Sanji', job: 'Chef' }
];
Writing the Data-Driven Test
Next, write a test script that iterates over the test data and runs the test with each set of values. Here's how you can do it:
import { test, expect } from '@playwright/test';
const testData = [
{ name: 'Luffy', job: 'Pirate' },
{ name: 'Zoro', job: 'Swordsman' },
{ name: 'Sanji', job: 'Chef' }
];
testData.forEach((data) => {
test(`Create a new user with name ${data.name}`, async ({ request }) => {
const response = await request.post('/api/users', { data });
expect(response.ok()).toBeTruthy();
const user = await response.json();
expect(user.name).toBe(data.name);
});
});
Running the Test
Now, run the test script. Playwright will execute the test multiple times, once for each set of data in the array.
To wrap up, let's address some frequently asked questions about API testing with Playwright:
response
object. You can use methods like response.ok()
to check the status and response.json()
to parse the response body, as shown in the examples above.And there we have it! I hope this guide serves as a helpful starting point for your API testing journey with Playwright. As we've seen, Playwright is not only a powerful tool for UI testing but also offers robust capabilities for API testing.
By following this guide, you've learned how to set up a Playwright project, write tests for various API requests, and implement data-driven testing to enhance your test coverage. Now, it’s time for you to start writing your own API tests. Remember, the best way to learn is by doing, so don't hesitate to get your hands dirty and start writing some tests!
If you found this guide helpful and want to dive even deeper, check out this comprehensive Playwright Testing Course for Beginners. This course is designed to equip you with the skills and knowledge to become proficient in Playwright, guiding you from a beginner to an expert level. Don't miss this opportunity to further enhance your skills and become a master in Playwright testing!
The course mentioned is offered through my personal website, SDET Unicorns, and I will earn revenue from any course purchases. This helps to support the site and allows me to continue creating content like this. Thank you for your support.
Happy testing!