Write an after-response script to test a response in Insomnia

Uses: Insomnia
TL;DR

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

Download and install Insomnia.

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: Run in Insomnia

This pre-configured collection contains:

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:

  1. In Insomnia, navigate to the “Flight Service 0.1.0” document.
  2. Click the Collection tab in the sidebar.
  3. In the sidebar of your collection, select the Get KongAir planned flights request.
  4. Open Scripts > After-response.
  5. 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.
  6. 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, and insomnia.expect() creates an assertion on the value of the route_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.

Something wrong?

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!