Introduction

Automated API testing is a cornerstone of modern DevOps and CI/CD pipelines. While UI testing has its place, API testing is often faster, more reliable, and more comprehensive. This guide will delve into automated data-driven API testing using Playwright and TypeScript. We’ll cover everything from setting up your environment to writing and running your tests.

Setting Up Your Environment

Prerequisites

  • Node.js and npm
  • TypeScript
  • Playwright

First, let’s install Node.js and npm if you haven’t already. You can download the installer from https://nodejs.org.

To use Playwright with TypeScript, we must initiate a new project and select TypeScript as a working language. Playwright supports TypeScript out of the box.

In the terminal, run the following command to initiate a new project:

npm init playwright@latest

  • Next, select TypeScript as a working language
  • Select the Name of your Tests folder
  • Select the option to add a GitHub Actions workflow to run tests on CI (optional) easily
  • Select the option NOT to install Playwright browsers, as they are not needed for API testing

Once the installation is complete, we can start writing our first Playwright test.

Writing Your First API Test

Let’s write a simple test to validate the response from a REST API endpoint. We’ll use the JSONPlaceholder API for demonstration.

Create a new file api.test.ts in the tests folder and add the following code:

import { expect, test } from '@playwright/test';
test('Should return a list of users', async ({ request }) => {
  const response = await request.get('https://jsonplaceholder.typicode.com/users');
  const responseJson = await response.json();
  expect(response.status()).toEqual(200);
  expect(responseJson.length).toBeGreaterThan(0);
});

Run the test:

npx playwright test

Data-Driven Testing

Data-driven testing allows you to run the same test with multiple data sets. This is particularly useful for APIs where you want to validate different query parameters, payloads, or headers.

Parameterized Tests

The playwright supports parameterized tests. You can parameterize tests on a test level. Here’s an example:

import { expect, test } from '@playwright/test';
test.describe('Data-Driven API Tests', () => {
  const testCases = [
    { id: 1, name: 'Leanne Graham', email: 'Sincere@april.biz' },
    { id: 2, name: 'Ervin Howell', email: 'Shanna@melissa.tv'  },
    { id: 3, name: 'Clementine Bauch', email: 'Nathan@yesenia.net' },
  ];
  for (const testCase of testCases) {
    test(`Should return correct user for ID ${testCase.id}`, async ({ request }) => {
      const response = await request.get(`https://jsonplaceholder.typicode.com/users/${testCase.id}`);
      const responseJson = await response.json();
      expect(response.status()).toEqual(200);
      expect(responseJson.name).toEqual(testCase.name);
      expect(responseJson.email).toEqual(testCase.email);
    });
  }
});

Parameterized Tests using CSV files

The Playwright test runner operates within Node.js, allowing you to effortlessly read files from your system and process them using your favorite CSV library.

Take this sample CSV file named users-test-input.csv for instance:

"id","name","email"
"1","Leanne Graham","Sincere@april.biz"
"2","Ervin Howell","Shanna@melissa.tv"
"3","Clementine Bauch","Nathan@yesenia.net"

We’ll create a few tests using this data, leveraging the csv-parse library available on NPM. Here’s an example:

test.describe('Data-Driven API Tests', () => {
  const testCases = parse(fs.readFileSync(path.join(__dirname, 'users-test-input.csv')), {
    columns: true,
    skip_empty_lines: true
  });
  for (const testCase of testCases) {
    test(`Should return correct user for ID ${testCase.id}`, async ({ request }) => {
      const response = await request.get(`https://jsonplaceholder.typicode.com/users/${testCase.id}`);
      const responseJson = await response.json();
      expect(response.status()).toEqual(200);
      expect(responseJson.name).toEqual(testCase.name);
      expect(responseJson.email).toEqual(testCase.email);
    });
  }
});

Conclusion

Automated data-driven API testing is a powerful approach to ensure the robustness of your application. Playwright and TypeScript offer rich features to make API testing efficient and maintainable. From setting up your environment to writing advanced, data-driven tests, you now have the tools to create a comprehensive API testing suite.

Explore our blog for advanced tutorials, and don’t miss our article Playwright Reporters: How to Integrate with Azure DevOps Pipelines.

References

0 Shares
Tweet
Share
Share