Skip to content
Anudeep edited this page Sep 27, 2020 · 22 revisions

pactum

Build Coverage Downloads Size Platform

pactum is a REST API Testing Tool used to write e2e, integration, contract & component (or service level) tests. It comes with a powerful mock server which can control the state of external dependencies & combines the implementation of a consumer-driven contract library Pact for JavaScript.

This library can be integrated with test runners like cucumber, mocha, jest or any other runners. It is simple, fast, easy and fun to use.

Documentation

This readme offers an introduction to the library. For more information visit the following links.

Installation

# install pactum as a dev dependency
npm install --save-dev pactum

# install a test runner to run pactum tests
# mocha / jest / cucumber
npm install --save-dev mocha

Usage

pactum can be used for all levels of testing in a test pyramid. It can also act as an standalone mock server to generate contracts for consumer driven contract testing.

API Testing

Tests in pactum are clear and comprehensive. It uses numerous descriptive methods to build your requests and expectations. Learn more about these methods at API Testing.

Simple Test Cases

Using Mocha

Running simple api test expectations.

const pactum = require('pactum');

it('should be a teapot', async () => {
  await pactum.spec()
    .get('http://httpbin.org/status/418')
    .expectStatus(418);
});

it('should save a new user', async () => {
  await pactum.spec()
    .post('https://jsonplaceholder.typicode.com/users')
    .withHeaders('Authorization', 'Basic xxxx')
    .withJson({
      name: 'bolt',
      email: '[email protected]'
    })
    .expectStatus(200);
});
# mocha is a test framework to execute test cases
mocha /path/to/test

Using Cucumber

See pactum-cucumber-boilerplate for more details on pactum & cucumber integration.

// steps.js
const pactum = require('pactum');
const { Given, When, Then, Before } = require('cucumber');

let spec = pactum.spec();

Before(() => { spec = pactum.spec(); });

Given('I make a GET request to {string}', function (url) {
  spec.get(url);
});

When('I receive a response', async function () {
  await spec.toss();
});

Then('response should have a status {int}', async function (code) {
  spec.response().should.have.status(code);
});
Scenario: Check TeaPot
  Given I make a GET request to "http://httpbin.org/status/418"
  When I receive a response
  Then response should have a status 200

Complex HTTP Assertions

It allows verification of returned status codes, headers, body, json objects, json schemas & response times. Learn more about available assertions at API Testing

Running complex component test expectations.

it('should have a user with id', () => {
  return pactum.spec()
    .get('https://jsonplaceholder.typicode.com/users/1')
    .expectStatus(201)
    .expectHeaderContains('content-type', 'application/json')
    // performs partial deep equal
    .expectJsonLike([
      {
        "id": /\d+/,
        "name": "Bolt",
        "address": [
          {
            "city": "NewYork"
          }
        ]
      }
    ])
    .expectJsonSchema({
      type: 'array',
      items: {
        type: 'object',
        properties: {
          id: {
            type: 'number'
          }
        }
      }
    })
    .expectJsonQueryLike('[0].address[*].city', ['Boston', 'NewYork'])
    .expectResponseTime(100);
});

It also allows us to break assertions into multiple steps that makes our expectations much more clearer.

const pactum = require('pactum');
const expect = pactum.expect;

describe('Chai Like Assertions', () => {

  let spec = pactum.spec();
  let response;

  it('given a user is requested', () => {
    spec.get('http://localhost:9393/api/users/snow');
  });

  it('should return a response', async () => {
    response = await spec.toss();
  });

  it('should return a status 200', () => {
    expect(response).to.have.status(200);
  });

  it('should return a valid user', async () => {
    spec.response().to.have.json({ name: 'snow'});
  });

});

We can also add custom expect handlers that are ideal to make much more complicated assertions by taking advantage of popular assertion libraries like chai

await pactum.spec()
  .post('https://jsonplaceholder.typicode.com/posts')
  .withJson({
    title: 'foo',
    body: 'bar',
    userId: 1
  })
  .expectStatus(201)
  .expect(({res}) => { /* Custom Assertion Code */ });

Data Management

Data management is made easy with this library by using the concept of Data Templates & Data References. You can reuse data across tests. Learn more about data management with pactum at Data Management

const stash = pactum.stash;

stash.addDataTemplate({
  'User.New': {
    FirstName: 'Jon',
    LastName: 'Snow'
  }      
});

await pactum.spec()
  .post('/api/users')
  // json will be replaced with above template & overrides last name
  .withJson({
    '@DATA:TEMPLATE@': 'User.New',
    '@OVERRIDES@': {
      'LastName': 'Dragon'
    }
  });

Nested Dependent HTTP Calls

API testing is naturally asynchronous, which can make tests complex when these tests need to be chained. With Pactum, passing response data to the next tests is very easy.

  • returns allows us to return custom data from the response using json-query or custom handler functions.
  • stores allows us to save response data under data management which can be referenced later using json-query.

Learn more about it at API Testing

const pactum = require('pactum');
const expect = require('chai').expect;

it('should return all posts and first post should have comments', async () => {
  const postID = await pactum.spec()
    .get('http://jsonplaceholder.typicode.com/posts')
    .expectStatus(200)
    .returns('[0].id');
  const response = await pactum.spec()
    .get(`http://jsonplaceholder.typicode.com/posts/${postID}/comments`)
    .expectStatus(200);
  const comments = response.json;
  expect(comments).deep.equals([]);
});

it('should return all posts and update first posts title', async () => {
  const postID = await pactum.spec()
    .get('http://jsonplaceholder.typicode.com/posts')
    .expectStatus(200)
    .stores('FirstPostId', '[0].id');
  const response = await pactum.spec()
    .patch(`http://jsonplaceholder.typicode.com/posts`)
    .withJson({
      id: '@DATA:SPEC::FirstPostId@',
      title: 'new title'
    })
    .expectStatus(200);
});

Retry Mechanism

Some API operations will take time & for such scenarios pactum allows us to add custom retry handlers that will wait for specific conditions to happen before attempting to make assertions on the response. (Make sure to update test runners default timeout)

await pactum.spec()
  .get('https://jsonplaceholder.typicode.com/posts/12')
  .retry({
    count: 2,
    delay: 2000,
    strategy: ({res}) => { return res.statusCode === 202 }
  })
  .expectStatus(200);

Learn more about api testing with pactum at API Testing

Component Testing

Component testing is defined as a software testing type, in which the testing is performed on each component separately without integrating with other components. So the service under test might be talking to a mock server, instead of talking to real external services.

Pactum comes with a mock server where you will able to control the behavior of each external service. Interactions are a way to instruct the mock server to simulate the behavior of external services. Learn more about interactions at Interactions.

Running a component test expectation with mocking an external dependency.

const pactum = require('pactum');

before(() => {
  // starts a mock server on port 3000
  return pactum.mock.start(3000);
});

it('should get jon snow details', () => {
  return pactum.spec()
    // adds interaction to mock server & removes it after the spec
    .useMockInteraction({
      withRequest: {
        method: 'GET',
        path: '/api/address/4'
      },
      willRespondWith: {
        status: 200,
        body: {
          city: 'WinterFell',
          country: 'The North'
        }
      } 
    })
    .get('http://localhost:3333/users/4')
    .expectStatus(200)
    .expectJson({
      id: 4,
      name: 'Jon Snow',
      address: {
        city: 'WinterFell',
        country: 'The North'
      }
    });
});

after(() => {
  return pactum.mock.stop();
});

Learn more about component testing with pactum at Component Testing

Contract Testing

Contract Testing is a technique for testing interactions between applications (often called as services) that communicate with each other, to ensure the messages they send or receive conform to a shared understanding that is documented in a contract.

Learn more about contract testing at pact.io

Learn more about contract testing with pactum at Contract Testing

Contract Testing

Contract Testing has two steps

  1. Defining Consumer Expectations (Consumer Testing)
  2. Verifying Expectations on Provider (Provider Verification)

Consumer Testing

Running a consumer test with the help of a mock server & a single pact interaction. If the pact interaction is not exercised, the test will fail.

const pactum = require('pactum');
const mock = pactum.mock;
const consumer = pactum.consumer;

before(async () => {
  consumer.setConsumerName('consumer-service');
  await mock.start();
});

it('GET - one interaction', async () => {
  await pactum.spec()
    .usePactInteraction({
      provider: 'projects-service',
      state: 'when there is a project with id 1',
      uponReceiving: 'a request for project 1',
      withRequest: {
        method: 'GET',
        path: '/api/projects/1'
      },
      willRespondWith: {
        status: 200,
        headers: {
          'content-type': 'application/json'
        },
        body: {
          id: 1,
          name: 'fake'
        }
      }
    })
    .get('http://localhost:9393/api/projects/1')
    .expectStatus(200)
    .expectJsonLike({
      id: 1,
      name: 'fake'
    });
});

after(async () => {
  await mock.stop();
  await consumer.publish(/* publish options */);
});

Learn more about pactum as a consumer tester at Consumer Testing

Provider Verification

Running a provider verification test with the help of a pact broker.

await pactum.provider.validate({
  pactBrokerUrl: 'http://pact-broker:9393',
  providerBaseUrl: 'http://user-service:3000',
  provider: 'user-service',
  providerVersion: '1.2.3'
});

Learn more about pactum as a provider verifier at Provider Verification

Mock Server

Mock Server allows you to mock any server or service via HTTP or HTTPS, such as a REST endpoint. Simply it is a simulator for HTTP-based APIs.

pactum can act as a standalone mock server or as a service virtualization tool. It comes with a powerful request & response matching and out of the box Data Management.

Running pactum as a standalone mock server.

const pactum = require('pactum');
const { regex } = pactum.matchers;

pactum.mock.addMockInteraction({
  withRequest: {
    method: 'GET',
    path: '/api/projects',
    query: {
      date: regex(/^\d{4}-\d{2}-\d{2}$/)
    }
  },
  willRespondWith: {
    status: 200,
    headers: {
      'content-type': 'application/json'
    },
    body: {
      id: 1,
      name: 'fake'
    }
  }
});

pactum.mock.start(3000);

Learn more about pactum as a mock server at Mock Server

Notes

Inspired from frisby testing style & pact interactions.


API Testing