loading...
Cover image for How to Automate Creating API Tests for Postman with Moesif
moesif

How to Automate Creating API Tests for Postman with Moesif

kayis profile image K Originally published at moesif.com ・6 min read

Cover image by Joshua Sortino on Unsplash

We all have our favorite tools when creating our APIs. One of the major players here is Postman. A graphical HTTP API client that allows us to construct, send, and save requests to an API of our choice.

Moesif API Analytics even allows us to generate Postman collections from the real requests it collected from our users.

Save and manage requests

The ability to save requests and manage them in collections and folders is the basis for test automation because with every request, folder, and collection, we can also save two scripts. Postman executes these scripts before and after a request happened.

These collections can then be exported as JSON files and run via a CLI tool called Newman. This export allows us to version all our requests, write tests for them with a friendly UI tool, and then integrate them in our CI/CD pipeline.

To integrate test scripts with Postman requests, we have to create a new collection first. For a simple API, we can use one collection for the whole API.

To create a collection, we have to do the following steps:

  1. Click on the Collections tab in the left sidebar
  2. Click on New Collection inside the Collections tab
  3. Enter a name for the new collection, like "My API"
  4. Click Create

With a collection to hold our requests, we can now define these requests.

To create a request, we have to follow these steps:

  1. Right-click on the new collection
  2. Select Add Request
  3. Enter a request a name
  4. Click Save to My API

The new request shows up in the left sidebar under the new collection we created. It won't have any target URL, so it can't be sent at the moment.

If we click on the request, we can Enter request URL. Let's enter example.com and click Send!.

Postman sends a GET HTTP request to the example.com server, which, in turn, responds with an HTML page.

If we now click Save, our request is updated inside the collection we created before.

Integrate tests with requests

Now that we have saved our request, we can load it every time we start Postman and do it again.

We can even export the collection it resides in by clicking on ... in the lower right corner of our collection in the left sidebar and selecting Export. This export creates a JSON file; we can share it with other developers and put inside version control.

The next thing we have to do is adding scripts to our requests.

There are two types of scripts:

  1. Pre-requests Scripts, which are executed before the request is sent
  2. Tests, which are executed after a response has been received

If we select our request, we can see Pre-requests Script and Test tabs below the text field where we entered our target URL.

Let's add a test script by selecting the Test tab and pasting the following code into the text area:

pm.test("response is ok", () => {
  pm.response.to.have.status(200);
});

When we click Send at the top right, the code is executed after Postman has received a response. In this test, we simply check if the response has a 200 status.

We can see the result of this test after we clicked Send; we just have to scroll down; under the text area, we used to enter the test. It's in the tab Test Results (1/1).

When we click Save, our test is saved besides our request inside our collection. If we export it later, it can be found as a string inside our collection JSON.

Writing tests

Right beside the text area, we can find code-snippets and a link to the scripts' documentation of Postman. These code-snippets also exist for Pre-requests Scripts; they can be used to dynamically generate parts of our requests, like headers or parameters.

Let's write a bit more complex test, with the help of a snippet!

For this, we first delete our test code and then click on a snippet on the right side of the text area.

Select Response body: Contains string

This generates the following code:

pm.test("Body matches string", function () {
  pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});

This snippet extracts the text of our response and tries to find a specific string in it.

To find an actual string in our response from example.com, we need to scroll down and select the Body tab.

Here we see the HTML that got delivered. We can select a part of it and use it in our test instead of the "string_you_want_to_search" placeholder.

Let's select This domain is for use in illustrative examples in documents. and update our test, so it looks like the following:

const expectedText = "This domain is for use in illustrative examples in documents.";
pm.test("Body matches string", function () {
  pm.expect(pm.response.text()).to.include(expectedText);
});

If we click Send again, we can see under Test Results that our test works.

Exporting tests

The next step is exporting our test so we can use it in our CI/CD pipeline. To do so, we need to export our collection, which then includes our tests.

Exporting a collection is done by clicking on the ellipsis symbol (...) of our collection on the left sidebar and selecting Export from the context menu.

In the dialog, we select Collection v2.1, because Postman recommends us doing so and then click Export.

The export format is a bit crude but human-readable. The tests are JSON strings with JavaScript so that they can be manipulated with an editor, but using Postman gives us at least some IDE features.

Running tests via Newman CLI

Now that we have exported our collection in the JSON format, we can use this exported file to run our tests in the command line.

A CLI tool called newman is used to run Postman collections in the command line.

When we execute it with the run command and supply the path to our exported collection file, it tries to send all the requests we defined and execute the test scripts.

For our My API collection this could look like that:

$ npx newman run My\ API.postman_collection.json

It is also possible to install Newman globally with brew if NPM isn't available.

Creating Postman collections with Moesif

Moesif allows us to generate Postman collections from real user requests. This allows us to debug our APIs locally with real data! We can also integrate requests in our test-suite later, to run it with newman in our CI/CD pipeline, so we can be safe that requests that led to issues in the past are not part of any regression errors.

To create a collection with Moesif, we have to follow these steps:

  1. Log into Moesif
  2. Click the API Analytics tab at the top
  3. Select the requests we like to include into the collection
  4. Click Run In Postman
  5. Click Download Postman Collection

The generated collection can then be imported into the Postman UI application and then add tests or modify the requests so they can be used with the Newman CLI tool.

Conclusion

Postman is a very versatile tool that can help us build and test our APIs. If we export our collections and write tests for them, Postman becomes even more powerful in conjunction with Newman.

We can write our test with a friendly UI, export them to JSON so it can be stored alongside our API code. The export allows for easy version control and integration with CI/CD pipelines.

Moesif lowers the effort of creating these tests by allowing us to export request collections for Postman that are generated from real user requests, so we can harden our test suites, by replacing assumptions with real data.

When new developers check out our code, they can simply fire up Postman and run a few requests with their corresponding tests to do their work, so it even helps with onboarding.


Moesif is the most advanced API Analytics platform, supporting REST, GraphQL and more. Thousands of API first teams use Moesif to monitor their APIs and optimize their customer experience. Learn More


This article was originally written for the Moesif blog.

Posted on by:

kayis profile

K

@kayis

Taking care of developer relations at Moesif and creating educational content at fllstck.dev

moesif

Moesif is the most advanced API analytics platform for platform teams. Thousands of companies use Moesif API analytics for REST and GraphQL APIs to make smarter decisions and build for growth.

Discussion

pic
Editor guide