JavaScript: REST API Automation with PactumJS — Basics

Anudeep
4 min readApr 11, 2021

PactumJS is a free & open-source REST API Automation library for all levels in a Test Pyramid written in JavaScript.

Write general, component, integration, contract & e2e tests for REST APIs with this library.

There are many HTTP client, HTTP server & assertion packages available in the Node.js ecosystem, but PactumJS is particularly designed for testing. It is inspired by frisby & pact. Imagine PactumJS as a combination of HTTP client (request) + HTTP server (express) + assertions (chai) that makes testing REST APIs fun & easy. It has different ingredients that make this library powerful yet simple & lightweight.

Features

  • Compelling Mock Server
  • Elegant Data Management
  • Extendable & Customizable
  • Component, Contract, E2E & Fuzz Testing of APIs
  • Clear & Comprehensive Testing Style
  • Rich Set of Assertions on JSON responses

Getting Started

Step 1: Install Node.js & ensure it is working.

node -v
npm -v

Step 2: Start a new project by creating a new folder (test-rest)& initialize the project by navigating into it.

cd test-rest
npm init -y

Step 3: Install pactum (PactumJS) & a test runner. This library works with any test runner that supports promises. Here we are using mocha.

npm install pactum mocha

This library can also be integrated with other popular test runners like cucumber, jest, jasmine, etc.

Step 4: Create a folder “tests” and add a file “http.test.js” where we are going to write some tests.

Step 5: Update the “test” scripts tag in the package.json file to run the tests that are lying inside the tests folder => mocha tests

Project Folder Structure

Step 6: Running Tests

With the above setup, mocha will run all the .js files that are lying inside the tests folder.

npm run test

Writing Tests

PactumJS uses a clear & comprehensive test style to make the API tests more readable & maintainable.

For starters the spec() method will provide numerous methods to build HTTP requests & expectations. We can chain these methods to form a single test case or break them to write tests in BDD format. By placing a await statement before pactum.spec() will perform the request & specified assertions & at last, it will return the entire response.

Making a GET request

Add the below code in your “http.test.js” file.

  • Line #1: Imports PactumJS library.
  • Line #3 & #5 : Syntax from mocha to define a test suite & test case.
  • Line #6: Returns the instance of spec to build requests & expectations.
  • Line #7: Performs an HTTP GET request on the given URL.
  • Line #8: Expects 418 as the response status code.
Demo

If a test fails, this library will print the entire request & response in the terminal for troubleshooting the failures.

Making a POST request

To make a POST request, use post('url') method & withJson() method to attach a JSON body to the request.

Similarly, PactumJS provides numerous methods to pass additional data to the requests. For example

  • withHeaders() — to pass headers
  • withQueryParams() — to pass query params
  • withPathParams() — to pass path params
  • withFile() — to upload files
  • withForm() — to pass form data
  • withAuth() — to pass basic auth details
  • withFollowRedirects() — to follow redirects

Assertions

This library comes with a rich set of assertions to validate the content of the response. Just chain multiple assertion methods to validate the response in a lot of different ways.

Few of the available assertion methods are

  • expect() — custom exception handler
  • expectStatus() — expect response status code
  • expectHeader() — expect headers
  • expectJson() — expect exact JSON
  • expectJsonLike() — expect partial JSON
  • expectJsonMatch() — expect JSON with matchers
  • expectJsonSchema() — expect JSON schema
  • expectResponseTime() — expect response time

Nested HTTP Calls

Passing data between tests is always been a challenge in API testing. This library solves this issue in an elegant way that makes tests very clear & maintainable.

Let's look at an example of creating a user by making a POST request & then asserting the newly created user by making a GET request with server-generated UserId.

Creating a new user

Request
POST https://reqres.in/api/users
{
"name": "morpheus",
"job": "leader"
}
Response
{
"name": "morpheus",
"job": "leader",
"id": "751",
"createdAt": "2021-04-10T09:13:50.864Z"
}

Asserting the newly created user

We need to save the "id" from the above response-body to fetch the newly created user in our next test case.

Request
GET https://reqres.in/api/users/751

By default await pactum.spec() returns the entire response. To save the id we can use the following code const userId = response.json.id;

To make things simpler, PactumJS has returns() and stores() methods to retrieve custom data from the response using json-query.

Returns

  • Line #6: saves the user "id" from the response.
  • Line #13: json-query expression to retrieve the "id" from the response.

Stores

  • Line #13: stores the "id" from the response as UserId under Data Management (a powerful concept in PactumJS)
  • Line #19: stored UserId can be retrieved using a special expression $S{<name>} => $S{UserId} => 751 (dynamic user id from server)

Learn more about it at Integration Testing.

Conclusion

In this article, we have seen the basic introduction to PactumJS. It offers a lot more features that ease testing REST APIs.

Head over to the full documentation at https://pactumjs.github.io to learn more.

--

--