DEV Community

Cover image for Data-Driven API testing with Playwright: Step-by-step πŸ‘¨πŸΌβ€πŸ’»πŸž
Alleluia Izimpamvu
Alleluia Izimpamvu

Posted on

Data-Driven API testing with Playwright: Step-by-step πŸ‘¨πŸΌβ€πŸ’»πŸž

Introduction

In modern web development, ensuring that your API behaves as expected in various scenarios is critical. Automated testing plays a crucial role in this process, and data-driven testing is a popular approach. This article will explore how to perform API data-driven testing using Playwright with JavaScript. We'll cover the prerequisites, and setup process, and provide a step-by-step guide to implementing a test script that validates API responses against predefined data. Additionally, we'll demonstrate how to retrieve specific user data by using the Users and Posts open APIs as examples.

Pre-requisites

Before diving into the setup, ensure that you have the following prerequisites installed:

1. Install Node.js 18+

npm i node@lts

You can also download it from the official Node.js website

2. Install playwright

You can read my previous article on Playwright installation πŸ‘‰πŸ½here or read more information about playwright on the official Playwright website

3. Set up dotenv

We will use dotenv to load environment variables from a .env file. This will help keep the API URLs and sensitive data like API keys or tokens out of the code whenever necessary.

Install dotenv with the following command:

npm install dotenv --save

More information about the package Is found πŸ‘‰πŸ½here

API Test Script πŸ§‘β€πŸ’»

In this section, we'll will explain the playwright config file and write a Playwright test script to verify API endpoints if the response is Ok(200). The script performs two key actions:

  • Fetches a list of users and finds a user with ID 7.
  • Retrieves posts and filters them by User ID 7.

After we will explain each line of the code

4. Playwright Config file

Normally while you install Playwright this file name playwright.config.js has configuration about the browsers, default test folder, retries etc. you can delete the existing config and write API config as below:

import { defineConfig } from "@playwright/test";
import 'dotenv/config';

export default defineConfig({
    use:{
        baseURL: process.env.URL ,
        extraHTTPHeaders:{
          //Here you will pass all headers, if you have authentication token you can do it here
            'Content-Type': 'application/json',

        }
    },
    trace: 'on-first-retry',
    headless:true,
    retries:2,
})
Enter fullscreen mode Exit fullscreen mode

5. Write test scripts

Inside the tests directory, create a file *.spec.js and below is the code snippet:

import { test, expect } from "@playwright/test";
import 'dotenv/config';

test.describe(" User and Post API Tests", () => {
    test("Getting the List of the Users and getting user with ID 7", async ({ request }) => {
        // Make the API request to get users
        const res = await request.get(`${process.env.URL}/users`);

        // Validate response status and body
        expect(res.status()).toBe(200);
        expect(res.ok()).toBeTruthy();

        // Parse the response body
        const users = await res.json();

        // Find the user with ID 7
        const user = users.find(user => user.id === 7);
        if (!user) {
            console.error("User with ID 7 not found");
            return;
        }

        // Log the username for verification
        const username = user.name;
        console.log(`Username: ${username}`);

        // Store username in process.env for the next test to use
        process.env.USERNAME = username;
    });

    test("Testing getting Posts and posts by User ID 7", async ({ request }) => {
        const username = process.env.USERNAME;

        // Check if username is available
        if (!username) {
            console.error("Username not found. Make sure the user test ran successfully.");
            return;
        }

        console.log(`Posts by ${username}`);
        console.log('-------------------------');

        // Make the API request to get posts
        const res = await request.get(`${process.env.URL}/posts`);

        // Validate response status and body
        expect(res.status()).toBe(200);
        expect(res.ok()).toBeTruthy();

        // Parse the response body
        const posts = await res.json();

        // Filter posts to only include those with userId equal to 7
        const userPosts = posts.filter(post => post.userId === 7);

        for (const post of userPosts) {
            console.log(`Post ID: ${post.id}, Title: ${post.title}`);
        }
    });
});

Enter fullscreen mode Exit fullscreen mode

6. Script breakdown

Section 1: Importing Required Dependencies

Importing Dependencies

  • @playwright/test: This is Playwright's testing framework. We use its test and expect functions to write test cases and assertions.
  • dotenv/config: Loads environment variables from a .env file, allowing us to access sensitive data like API URLs.

Section 2: Describing the test suite

Describing the test suite

This block defines a test suite named "User and Post API Tests". The test.describe function groups related tests.

Section 3: First Test case: Fetching Users and Retrieving Specific User

First Test case

  • We are fetching all users and retrieving the details of the user with id 7

  • The async ({ request }) allows Playwright to handle HTTP requests asynchronously.

  • Making API request to get all users we use request.get()

  • Validating the response and check that the API status code is 200 which indicate that success using this code line expect(res.status()).toBe(200) and res.ok() to confirm that the request was successful

  • Parsing the Response Body using .json() method parses the response into a JavaScript object. We can now access individual users within the users array.

  • Find the user with id 7 and store the username in .env file for future use in the other test cases( from line 17-18)

Section 4:Fetching Posts and Filtering by User ID

Fetching Post

Mostly scripts are the same as previous test cases except that here we are getting posts and filtering in posts and returning only the posts of a specific user. Therefore we will focus on filtering part

  • We parse the response and then use filter() to retrieve posts where userId equals 7, which refers to the specific user we’re testing
  • For each post authored by the user, we log its id and title.

7. Running the Tests

npx playwright test : This will trigger the Playwright test suites and all files under the tests folder or your default directory.

Conclusion

This test suite automates fetching user data and their related posts from an API. By breaking the process into small, reusable components, we ensure modularity and maintainability. Playwright's API testing capabilities, combined with environment variables, make it easier to automate API interactions and adapt to different environments.
πŸ‘‰πŸ½Here is the link to github repo for the source code

References

Happy testing!!🎭

Top comments (0)