paint-brush
Playwright API Testing: a Comprehensive Guide for Beginnersby@dilpreetj
7,895 reads
7,895 reads

Playwright API Testing: a Comprehensive Guide for Beginners

by Dilpreet JohalOctober 9th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Playwright is a Node.js library that allows you to automate Chromium, Firefox, and WebKit browsers. It's not just limited to UI testing; you can also perform API testing with it. In this blog, we will dive straight into setting up a project for API testing.
featured image - Playwright API Testing: a Comprehensive Guide for Beginners
Dilpreet Johal HackerNoon profile picture


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!

What is Playwright?

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.

Few Use Cases of APIs with Playwright Tests

  • Testing Your Server API: With Playwright, you can easily check your server's API by sending requests and checking the responses, all without having to open a webpage. This helps you make sure that your API is working properly before you launch it.
  • Setting Up the Server Before Testing: Before you start testing your web application, you might need to get your server ready in a certain way. Playwright can help you do this quickly and easily, saving you time and effort.
  • Checking Server Changes After Testing: After you've done some actions in the browser during a test, you can use Playwright to check that the right changes have happened on the server side. This helps you make sure that your application is reliable and working as it should.


These features are made possible through the use of APIRequestContext methods, making your API testing process smooth and efficient.

Setting Up Your New Playwright Project

Setting up a new project is a straightforward process. Here's how to set up your Playwright project:

Creating a New Project Directory

First, create a new project directory named playwright-api with these commands:

mkdir playwright-api
cd playwright-api

Initializing a New Playwright Project

Next, initialize the project with the following command:

npm init playwright@latest

Choosing the Right Options

During the initialization, there are several options to choose from. Here are the recommended choices:

  • Opt for TypeScript as the project language.
  • Save the tests in the tests directory.

Configuring Your Playwright Project for API Testing

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',
    },
  }
});

Writing Your First API Test with Playwright

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.

GET Request: Retrieving a List of Users

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:

  • We first import the necessary modules.
  • We then define a test case where we make a GET request to fetch the list of users.
  • We use expect to assert that the response is okay and the user list is not empty.

POST Request: Creating a New User

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:

  • We define a new test case to create a new user.
  • We make a POST request with the new user data.
  • We then assert that the response is okay and the user is created successfully.


Now, let's quickly go over how you can write tests for PUT and DELETE requests:

PUT Request: Updating a User

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');
});

DELETE Request: Removing a User

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();
});

Data-Driven Testing with Playwright

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.

Implementing Data-Driven Testing in Playwright

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:

  1. 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' }
    ];
    
  2. 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);
      });
    });
    
    
  3. Running the Test

    Now, run the test script. Playwright will execute the test multiple times, once for each set of data in the array.


    Running the test

Frequently Asked Questions

To wrap up, let's address some frequently asked questions about API testing with Playwright:

  1. Can Playwright be used for API testing?
    • Absolutely, Playwright is not just limited to UI testing; it can also be used for API testing, allowing you to automate your API tests efficiently.
  2. How do I check my API response in Playwright test?
    • In Playwright tests, you can check the API response using the 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.
  3. Which API is used to write test scripts?
    • Playwright provides its own set of APIs to write test scripts. These APIs offer various methods to interact with web pages and perform API testing, as demonstrated in this guide.
  4. Does Playwright require Node.js?
    • Yes, Playwright is a Node.js library, and you need to have Node.js installed in your system to use Playwright for writing and running your tests.

Conclusion

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!


Disclaimer

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!