Write an after-response script to test a response in Insomnia
In your request, go to Scripts > After-response and use insomnia.test()
to create a test, then write the code for the test and send the request to validate it.
Prerequisites
Create and configure a collection
For this tutorial, you’ll need a collection in Insomnia. A collection is essential for this tutorial to function, but creating one isn’t the focus of this guide. Use the following to add a pre-configured collection to Insomnia:
This pre-configured collection contains:
- The example “Flights Service 0.1.0” spec added as a document
- A collection generated from the spec
- Pre-configured base environment variables
Add an after-response script
In this example, we’ll configure an after-response script that checks the value of a JSON field in a response:
- In Insomnia, navigate to the “Flight Service 0.1.0” document.
- Click the Collection tab in the sidebar.
- In the sidebar of your collection, select the Get KongAir planned flights request.
- Open Scripts > After-response.
- In the bottom pane, click Response Handling > Get body as JSON. This will add code that creates a
jsonBody
variable that we can use to check the content of the response body. - Add the following content after the variable:
insomnia.test('Check the first route ID', () => { insomnia.expect(jsonBody[0].route_id).to.eql('LHR-JFK'); });
In this example,
insomnia.test()
creates a new test, andinsomnia.expect()
creates an assertion on the value of theroute_id
field in the first object of the array returned by the request.
Validate the after-response script
Now that we created an after-response script, we can validate it by sending a GET request to the /flights/
endpoint.
Click Send. You should get a 200
status code with a JSON array as the response. Go to the Tests tab in the right pane to check that the test passed.