<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Meenakshi Bhandari</title>
    <description>The latest articles on DEV Community by Meenakshi Bhandari (@meenakshi).</description>
    <link>https://dev.to/meenakshi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1192323%2F2ae6fa30-4d73-4a5a-b8cd-54888a3988b8.png</url>
      <title>DEV Community: Meenakshi Bhandari</title>
      <link>https://dev.to/meenakshi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/meenakshi"/>
    <language>en</language>
    <item>
      <title>Supercharge Your API Testing with Playwright and TypeScript</title>
      <dc:creator>Meenakshi Bhandari</dc:creator>
      <pubDate>Mon, 30 Oct 2023 08:59:33 +0000</pubDate>
      <link>https://dev.to/meenakshi/supercharge-your-api-testing-with-playwright-and-typescript-3f1o</link>
      <guid>https://dev.to/meenakshi/supercharge-your-api-testing-with-playwright-and-typescript-3f1o</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;API (Application Programming Interface) testing is a critical part of software development. Ensuring that APIs perform as expected is essential for delivering a seamless user experience. TypeScript, a statically typed superset of JavaScript, along with Playwright, can be a powerful combination for API automation in a type-safe manner. In this blog, we'll explore how to supercharge your API testing using Playwright and TypeScript.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Playwright?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Playwright is an open-source automation framework developed by Microsoft that allows you to interact with web applications in a browser-agnostic way. It natively supports TypeScript, making it a versatile choice for automation. While its primary purpose is web automation, Playwright can be extended for API testing using its powerful features.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Use Playwright with TypeScript for API Automation?&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Type Safety&lt;/strong&gt;: TypeScript enforces static typing, catching errors at compile time rather than runtime, which leads to more reliable code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Cross-Browser Compatibility&lt;/strong&gt;: Playwright supports multiple browsers like Chrome, Firefox, and WebKit, ensuring that your API tests are browser-agnostic.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Headless Mode&lt;/strong&gt;: Playwright can run tests in headless mode, which is crucial for running tests on CI/CD pipelines and servers without a graphical user interface.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Parallel Testing&lt;/strong&gt;: Playwright enables parallel test execution, reducing the time it takes to run your API tests.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Getting Started with API Automation Using Playwright and TypeScript&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's dive into the steps to get started with API automation using Playwright and TypeScript.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; Install node.js on your machine&lt;/p&gt;

&lt;p&gt;You can download it directly from the Node.js website and install it on your machine. Once installed, check the version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node -v
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Download and Install Visual Studio Code&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Open your integrated terminal and run the following command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir playwright-api-testing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4:&lt;/strong&gt; Open the directory&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd playwright-api-testing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 5:&lt;/strong&gt; You can install Playwright using npm or yarn, and another way is by VS Code Extension&lt;br&gt;
we can install the Playwright using the npm command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init playwright@latest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faap7xj6vg88cstcw5585.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faap7xj6vg88cstcw5585.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyf9p8ski356dcf2qgn0i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyf9p8ski356dcf2qgn0i.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
Now let's create a sample project and see some CRUD (Create, Read, Update, Delete) operations examples for an API using Playwright and TypeScript.&lt;/p&gt;

&lt;p&gt;For this example, we'll assume we are interacting with a hypothetical RESTful API for managing bookings. We will implement each of the CRUD operations: creating booking, get booking, updating booking, and delete booking.&lt;/p&gt;

&lt;p&gt;Update baseURL in the playwright.config.js file so you can use it in each endpoint testing without specifying them.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;baseURL: 'https://restful-booker.herokuapp.com'&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F65jrft4lnb5tvrwgkb5i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F65jrft4lnb5tvrwgkb5i.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;POST - Booking with static data specified in JSON file:&lt;/strong&gt;&lt;br&gt;
Create a folder with the name test-data and then add a JSON file with the name booking-details.json. In the booking-details file, mention all the booking details you must pass while making a POST call.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "firstname": "Alex",
    "lastname": "Lee",
    "totalprice": 2000,
    "depositpaid": true,
    "bookingdates": {
        "checkin": "2023-01-01",
        "checkout": "2023-02-15"
    },
    "additionalneeds": "Breakfast"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To create a new booking, we need to pass the data from JSON in POST request to the /booking endpoint, we need to provide the request body by using a JSON file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { test, expect } from '@playwright/test';
import bookingDetails from '../test-data/booking-details.json';

test('should be able to create a booking', async ({ request }) =&amp;gt; {
    const response = await request.post(`/booking`, {
        data: bookingDetails
    });
    console.log(await response.json());
    expect(response.ok()).toBeTruthy();
    expect(response.status()).toBe(200);
    const responseBody = await response.json()
    expect(responseBody.booking).toHaveProperty("firstname", "Alex");
    expect(responseBody.booking).toHaveProperty("lastname", "Lee");
    expect(responseBody.booking).toHaveProperty("totalprice", 2000);
    expect(responseBody.booking).toHaveProperty("depositpaid", true);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we first import the JSON data, store it in variable and then call this in the test under data. Once we receive a response we then assert by using expect condition for the Ok message and status code 200. Then assert the response body to check the key and value.&lt;br&gt;
Run the below mentioned command to execute the test:&lt;br&gt;
&lt;code&gt;npx playwright test post-req-jsonData.spec.ts&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzmgbr0ja7iagtylq2r5z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzmgbr0ja7iagtylq2r5z.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GET all bookings:&lt;/strong&gt;&lt;br&gt;
To get all bookings, we will use a GET request to the /booking endpoint&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { test, expect } from '@playwright/test';

test('should be get all the booking details', async ({ request }) =&amp;gt; {
    const response = await request.get("/booking");
    console.log(await response.json());
    expect(response.ok()).toBeTruthy();
    expect(response.status()).toBe(200);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the request is completed, we will receive the response. Here, we assert by using expect condition for the ok message and status code 200. Here we are also logging the entire output to the console. We can also get only the specific booking details by providing the booking id. &lt;br&gt;
example: &lt;code&gt;const response = await request.get('/booking/1');&lt;/code&gt;&lt;br&gt;
Run the following command:&lt;br&gt;
&lt;code&gt;npx playwright test get_booking_details.spec.js&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5wx3bp75lazug1o8r42a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5wx3bp75lazug1o8r42a.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Update a resource [PUT]:&lt;/strong&gt;&lt;br&gt;
It is used to update the current booking details.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { test, expect } from '@playwright/test';

let token

test('Update the booking details', async ({ request }) =&amp;gt; {

    // Create a Token to use in PUT request

    const response = await request.post(`/auth`, {
        data: {
            "username": "admin",
            "password": "password123"
        }
    });
    console.log(await response.json());
    expect(response.ok()).toBeTruthy();
    expect(response.status()).toBe(200);
    const responseBody = await response.json();
    token = responseBody.token;
    console.log("New Token is: " + token);

    // PUT
    const updateRequest = await request.put(`/booking/1`, {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Cookie': `token=${token}`,
        },
        data: {
            "firstname": "Alex",
            "lastname": "Lee",
            "totalprice": 2000,
            "depositpaid": true,
            "bookingdates": {
                "checkin": "2023-01-01",
                "checkout": "2023-03-15"
            },
            "additionalneeds": "Breakfast"
        }
    });
    console.log(await updateRequest.json());
    expect(updateRequest.ok()).toBeTruthy();
    expect(updateRequest.status()).toBe(200);
    const updatedResponseBody = await updateRequest.json()
    expect(updatedResponseBody).toHaveProperty("firstname", "Alex");
    expect(updatedResponseBody).toHaveProperty("lastname", "Lee");
    expect(updatedResponseBody).toHaveProperty("totalprice", 2000);
    expect(updatedResponseBody).toHaveProperty("depositpaid", true);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this test, we make a POST call to an endpoint /auth to generate the token, which needs to be passed along with the PUT request. Once we receive a response we will store it in a variable. Then we make a PUT call to an endpoint /booking/1 and pass the token in the header and body in the data. Then we receive the response and we assert it by using expect condition. We also assert the response body to check the key and value.&lt;br&gt;
Run the following command:&lt;br&gt;
&lt;code&gt;npx playwright test update_booking_details.spec.js&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9nzqt42764anasczntti.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9nzqt42764anasczntti.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Delete (DELETE) a Booking:&lt;/strong&gt;&lt;br&gt;
This is used to delete the existing booking from the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { test, expect } from '@playwright/test';

let token

test('delete the booking details', async ({ request }) =&amp;gt; {

    // Create a Token to DELETE request

    const response = await request.post(`/auth`, {
        data: {
            "username": "admin",
            "password": "password123"
        }
    });
    console.log(await response.json());
    expect(response.ok()).toBeTruthy();
    expect(response.status()).toBe(200);
    const responseBody = await response.json();
    token = responseBody.token;
    console.log("New Token is: " + token);

    // DELETE

    const deleteRequest = await request.delete(`/booking/1`, {
        headers: {
            'Content-Type': 'application/json',
            'Cookie': `token=${token}`
        }
    });
    expect(deleteRequest.status()).toEqual(201);
    expect(deleteRequest.statusText()).toBe('Created');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we generate a token that needs to be passed with the delete request. Then we store the token in a variable and make a delete call. We then pass the token in the header and receive a response which we can assert by using expect condition.&lt;br&gt;
Run the following command:&lt;br&gt;
&lt;code&gt;npx playwright test delete_booking_details.spec.js&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbo1x18xst1ymi56fmycc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbo1x18xst1ymi56fmycc.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;These examples demonstrate how to perform CRUD operations on an API using Playwright and TypeScript. You can adapt these scripts to your specific API and application needs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advanced API Testing with Playwright and TypeScript&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Take advantage of TypeScript's features to enhance your API automation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Type Definitions&lt;/strong&gt;: Leverage type definitions and interfaces to define the shape of your API responses, making your code more self-documenting.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Error Handling&lt;/strong&gt;: Implement robust error handling strategies using TypeScript's error handling mechanisms to handle unexpected scenarios gracefully.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Parameterization&lt;/strong&gt;: Use TypeScript's type-safe parameterization techniques to iterate through different input values and validate API responses.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Integration with Test Runners&lt;/strong&gt;: Integrate Playwright and TypeScript-based API tests with popular test runners like Jest or Mocha for structured test organization. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;CI/CD Integration&lt;/strong&gt;: Easily incorporate TypeScript-based Playwright API tests into your CI/CD pipelines for continuous testing and deployment.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Combining Playwright with TypeScript for API automation enables you to create robust, type-safe tests. TypeScript's static typing catches errors early in the development process, while Playwright offers cross-browser support and a range of features for API testing. By incorporating TypeScript-based Playwright API tests into your development workflow, you can ensure the reliability and quality of your software, leading to a more seamless user experience.&lt;/p&gt;

</description>
      <category>playwright</category>
      <category>typescript</category>
      <category>automation</category>
    </item>
  </channel>
</rss>
