Skip to content
Anudeep edited this page Mar 25, 2020 · 22 revisions

pactum

Build Coverage

pactum is a REST API Testing Tool that combines the implementation of a consumer driven contract library Pact for JavaScript.

In simple words, pactum helps in testing API endpoints. It comes with a HTTP server that acts as a mock which enables to control the state of all external dependencies. It is simple, fast, easy and fun to use.

Documentation

Learn more about pactum from following links

Installation

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

# install a test framework to run pactum tests
# mocha / jest / jasmine
npm install --save-dev mocha

Usage

pactum can be used for

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.

Running a single component test expectation.

const pactum = require('pactum');

it('should be a teapot', async () => {
  await pactum
    .get('http://httpbin.org/status/418')
    .expectStatus(418)
    .toss();
});
# mocha is a test framework to execute test cases
mocha /path/to/test

Running a complex component test expectation.

const pactum = require('pactum');

it('should add a new post', () => {
  return pactum
    .post('https://jsonplaceholder.typicode.com/posts')
    .withJson({
      title: 'foo',
      body: 'bar',
      userId: 1
    })
    .withHeaders({
      "Content-Type": "application/json; charset=UTF-8"
    })
    .expectStatus(201)
    .expectHeader('content-type', 'application/json; charset=utf-8')
    .expectJson({
      id: '1'
    });
});

Running a component test expectation with mocking external dependency (AWS DynamoDB).

const pactum = require('pactum');

before(() => {
  return pactum.mock.start();
});

it('should not get non existing user', () => {
  return pactum
    .addMockInteraction({
      withRequest: {
        method: 'POST',
        path: '/',
        headers: {
          'x-amz-target': 'DynamoDB_20120810.GetItem'
        },
        body: {
          Key: { UserName: { S: 'brave' } },
          TableName: 'Users'
        }
      },
      willRespondWith: {
        status: 200,
        body: { Items: [] }
      }
    })
    .get('http://localhost:3333/user')
    .withQuery('user', 'brave')
    .expectStatus(404);
});

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');

before(async () => {
  await pactum.mock.start();
});

it('GET - one interaction', async () => {
  await pactum
    .addPactInteraction({
      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'
    })
    .toss();
});

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

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.

Running pactum as a standalone mock server.

const pactum = require('pactum');
pactum.mock.setDefaultPort(3000);
pactum.mock.start();

Learn more about pactum as a mock server here


Component Testing