DEV Community

george_pollock
george_pollock

Posted on • Originally published at hvitis.dev on

5 ways to improve your automated POSTMAN tests.

Improve your POSTMAN tests.

The methods I am sharing in this article allow me to prepare more robust tests. Some example use cases would be:


Using 3rd party libraries in pre scripts

You want to create random numbers? use lodash library? jQuery? Chai assertions?Maybe you need some high level time operations for your scripts? MomentJS? No problem.

  • Passing, parsing URLs
  • Validating Schemas
  • Decoding, encoding keys, tokens with SHA256 (atob, btoa)

No problem. POSTMAN allows you to use 3rd party libraries in its sandbox. Next tips will be tightly connected with this information, so have as look before proceeding!

Passing prerequest to body

Let’s say SWAGGER tells you that in body you need to pass string as title:

swagger_postman

You can programaticaly change your body content in pre-request scripts so that e.g. each time you make a request you have different Job title.

First open your pre-request scripts tab, prepare your body and stringify it.

postman-pre-script

(code version in case you need to copy)

const title = "Boss' Assistant nr " + _.random(0, 10)

const preparedBody = {
    "title" : title
}

pm.environment.set("job_object", JSON.stringify(preparedBody))
Enter fullscreen mode Exit fullscreen mode

You have to set this body object as an environment, global or collection variable. Once you do it, before executing the script you just need to use it in body like that:

postman-pre-script-use

Now each time you execute this request you will get new Job title:

"title": "Boss' Assistant nr 5"
...
"title": "Boss' Assistant nr 2"
...
"title": "Boss' Assistant nr 6"
Enter fullscreen mode Exit fullscreen mode

Parsing data from HTMLs forms

General use case: There is some visible or hidden data within the HTML tags on the rendered page that you need to pass / verify / check.

Specific use cases: You have a page that has a login fields with generated token that you need for next request.

Let’s say that you make a request to some API and it redirects you to a page with input fields that have tokens assigned. That’s a common use case with SAML and SSO. You can practice here on a real use case. This login field has a token.

input-token

On requesting the URL of this page we will get just normal HTML:

postman-html-request

As you’ve read in a previous tip, we can use libraries provided in POSTMAN SandBox. jQuery is replaced by CheerioJS which emulates jQuery core API.

Let’s load the library and see if it’s working:

const $ = cheerio.load(pm.response.text())
console.log('Title of the page: ', $('title').text())
Enter fullscreen mode Exit fullscreen mode

Now you just need to use your selectors magic knowledge. Let’s query for the TOKEN we need:

console.log($('input[name=authenticity_token]').attr('value'))
Enter fullscreen mode Exit fullscreen mode

( TIP 1: If you are not good with selectors, click right mouse button on element you are looking for and then copy selector )

( TIP 2: If you need other information from HTML elements, check the Cheerio documentation for more. )

And finally let’s write the test and export the TOKEN:

pm.test('input field it should have a token', () => {
  let TOKEN = $('input[name=authenticity_token]').attr('value')
  pm.expect(TOKEN).to.not.be.empty
  pm.environment.set('TOKEN', TOKEN)
})
Enter fullscreen mode Exit fullscreen mode

Now you can use the TOKEN in other requests.

SetNextRequest

I’m assuming you know what is a postman collection. It’s a set of requests or folders with requests, depending how you order your work. The basic workflow that POSTMAN uses is checking request one after the other. It goes from the top to bottom basically. Most of this is well described already but I will just mention that with

postman.setNextRequest('REQUEST_NAME_HERE')
Enter fullscreen mode Exit fullscreen mode

You can go back to previous requests or skip some requests or loop through requests 7. It’s IMPORTANT to remember that naming convention in your requests that follows e.g. CamelCase and has consistent information helps tremendously because it makes your code cleaner.

Instead of using default naming:

postman-request-naming

Try naming your request in a way that will be easier to write them in the scripts when passing their names into your setNextRequest() e.g. using request method and no spaces:

good-postman-request-namingt

Validating schema

Imagine you make a test for checking if your API returns a Bank Account number.

const jsonData = pm.response.json()
pm.test('returns IBAN as a number', () => {
  const IBAN = jsonData.IBAN
  pm.expect(IBAN)
    .to.be.an('number')
    .that.does.not.include('ES')
})
Enter fullscreen mode Exit fullscreen mode

You assert that it should be a number and it works fine but what if you would need to be sure as per data types of an entire response of object with 50 keys? Using assertions would be cumbersome.

That’s a use case for schema validation. POSTMAN allows us to use

  • tv4 - Tiny Validator (for v4 JSON Schema) and / or
  • Ajv - Another JSON Schema Validator

The documentation for both libraries shows all the API you could use. I will just show you the basic idea behind it:

// We create a schema for our response
var schema = {
  IBAN: {
    type: 'number',
  },
}
Enter fullscreen mode Exit fullscreen mode

and write a test for it:

const jsonData = pm.response.json()
pm.test('Schema is valid', () => {
  pm.expect(tv4.validate(jsonData, schema)).to.be.true
})
Enter fullscreen mode Exit fullscreen mode

We could verify properties, whether field is required, nested objects, referencing and many more. Always remember to read documentation before starting to know the full potential of your tools!



Did you make any mistakes when using POSTMAN or you’ve seen one here? Tell me about your insights. Leave a comment with YOUR opinion.

Top comments (3)

Collapse
 
iamajeeth profile image
AjeethKumar_Ramesh

Do we need postman kind of apps to work with APIs?

Collapse
 
jsdevelopermano profile image
manoj

yes its easy to test with APIs, one of the best tool to use.

Collapse
 
ajm8dev profile image
ajm8dev

yes of course, what else than postman