API Test: How to assert JWT Token content using Postman
In this tutorial I will share how to assert jwt token in the response body. To simulate API behavior, I will use dummy API server from dummyjson.com. You can access the website using the link below:
In this simulation, I will use endpoint “Login user and get token”. This endpoint is using POST method. For how to test http method using postman you can follow the instruction from the article below:
The figure below is the response body for “Login and get token” endpoint. We want to assert the jwt content from “token” field.
To do that we can use atob()
. To use it you can write down the following script in the “Tests” tab.
jsonData=JSON.parse(responseBody);
const payload = jsonData.token.split(‘.’)[1];
const parsed = atob(payload);
console.log(parsed);
After we hit send button, postman will return log that contains the jwt content. Then we can assert tho content values.
To assert jwt token we can add following test script:
pm.test(“Jwt should include username”, function () {
pm.expect(parsed).to.include(“\”username\”:\”kminchelle\””)
});
We can assert another field by adding pm.expect script within the pm.test block, for example jwt token should contain field “firstname” with value “Jeanne“. We can add test script as following:
pm.test(“Jwt should include username”, function () {
pm.expect(parsed).to.include(“\”username\”:\”kminchelle\””)
pm.expect(parsed).to.include(“\”firstName\”:\”Jeanne\””)
});
Thanks for reading this article.
Follow me on
Facebook: https://www.facebook.com/mydoqa/
Instagram: https://www.instagram.com/mydoqa/
Twitter: https://twitter.com/MydoQa