May 29th, 2020 - written by Kimserey with .
Few weeks ago we looked into automating Postman collection run using Newman CLI. On top of using the CLI directly, Newman can also be used in a NodeJS application which makes it very versatile to create tools for testing. Today we will look at how we can use Newman as a NPM library and see the options provided.
Let’s start by exporting a sample collection in JSON format:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
"info": {
"_postman_id": "32a14dcc-18e2-4a9b-8614-58061829c75a",
"name": "Test Collection",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "GET petshop",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:5000/pets",
"protocol": "http",
"host": [
"localhost"
],
"port": "5000",
"path": [
"pets"
]
}
},
"response": []
}
],
"protocolProfileBehavior": {}
}
Then we can install Newman via NPM:
1
npm install newman --save
Next we can simply use it by calling the #.run(...)
function which runs the collection.
1
2
3
4
5
6
7
8
9
const newman = require('newman');
newman.run({
collection: require('./sample-collection.json'),
reporters: 'cli'
}, function (err) {
if (err) { throw err; }
console.log('collection run complete!');
});
#.run
takes an option
object which allows us to set different option that we would normally provide as CLI options.
Here we set collection
which is the JSON collection and reporters which is the summary reporter format which will be printed once the collection has completed its run.
The two other important parameter of the option is the environment
, it can either be defined as an object
or a string
path pointing to an environment varaible file exported through Postman.
For example we export the following environment:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"id": "85f1bf17-34ac-42af-a8bd-531ef44a19fb",
"name": "Example Env",
"values": [
{
"key": "HOST",
"value": "localhost",
"enabled": true
}
],
"_postman_variable_scope": "environment",
"_postman_exported_at": "2020-04-06T08:47:05.528Z",
"_postman_exported_using": "Postman/7.21.2"
}
And modify our collection to use the environment:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
"info": {
"_postman_id": "32a14dcc-18e2-4a9b-8614-58061829c75a",
"name": "Test Collection",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "GET petshop",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://{{HOST}}:5000/pets",
"protocol": "http",
"host": [
"{{HOST}}"
],
"port": "5000",
"path": [
"pets"
]
}
},
"response": []
}
],
"protocolProfileBehavior": {}
}
And we can now provide the path to our exported environment:
1
2
3
4
5
6
7
8
9
10
const newman = require('newman');
newman.run({
collection: require('./sample-collection.json'),
environment: './env.json',
reporters: 'cli'
}, function (err) {
if (err) { throw err; }
console.log('collection run complete!');
});
The second argument of #.run
is a callback returning an error
which would occur if Newman failed to run the collection due to some unexpected error - only fatal errors unrelated to request or test failing - and a summary
with the result of the collection.
So far we only did what we the CLI allowed us to do. But the advantage of running in a Node application is that we can ho9ok onto Newman events to build logic around it.
For example, we can hook onto start
to add some logic before the collection starts:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const newman = require('newman');
var token = "";
newman.run({
collection: require('./s.json'),
environment: './env.json',
reporters: 'cli'
}, function (err) {
if (err) { throw err; }
console.log('collection run complete!');
})
.on('start', function (err, args) {
token = retrieveToken();
})
.on('beforeRequest', function (err, args) {
args.request.headers.add({key: "authorization", value: token });
});
function retrieveToken() {
return "abc";
}
For example here we hook the start
of the collection with a function getting an authorization token and use beforeRequest
to add an authorization
header to each of the requests.
Another interesting event is request
which gets triggered after each request complete and extract the results to be displayed once the whole run is over.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const newman = require('newman');
var token = "";
var results = [];
newman.run({
collection: require('./s.json'),
environment: './env.json',
reporters: 'cli'
}, function (err) {
if (err) { throw err; }
console.log('collection run complete!');
})
.on('start', function (err, args) {
token = retrieveToken();
})
.on('beforeRequest', function (err, args) {
args.request.headers.add({key: "authorization", value: token });
})
.on('request', function (err, args) {
const res = JSON.parse(args.response.stream.toString());
results.append(res);
})
.on('done', function (err, args) {
console.log(results);
});
function retrieveToken() {
return "abc";
}
In this example we expect the result of the requests to be a JSON format so we can use JSON.parse(args.response.stream.toString())
to extract the JSON result from the response. And that concludes today’s post!
Today we looked at how we could use Newman as a NPM package library. We started by looking at how we could install it and run a collection. Then we moved on to look into how we could subscribe to events emitted by Newman to add custom logic with an example of authorization implementation and results aggregation. Using Newman as a library opens a lot of possibilities to script tools in JavaScript. One example would be to aggregate the results and build a custom HTML report using the results. I hope you liked this post and I see you on the next one!