v13.3+ Legacy unit tests are hidden by default.
If an API Collection already contains legacy unit tests, its Tests tab still appears automatically. Otherwise, to follow this guide, go to Preferences > General > Application and enable Show legacy unit tests, which shows the Tests tab on every API Collection.
For new work, use pre-request and after-response scripts instead. Scripts are the recommended way to test APIs in Insomnia.
Write tests for headers in the response in Insomnia
Legacy unit tests are hidden by default since Insomnia 13.3. After you enable them and add an API Collection, you can create a new test suite for the API Collection and then create individual tests in the suite.
Prerequisites
Create and configure an API Collection
For this tutorial, you’ll need an API Collection in Insomnia. An API 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 API Collection to Insomnia:
This pre-configured API Collection contains:
- The example “Flights Service 0.1.0” OpenAPI spec in its Spec tab
- Requests generated from the spec
- Pre-configured base environment variables
Create a test suite
Before you create a test, you need to create a test suite for your API Collection.
- If your API Collection doesn’t have a Tests tab, go to Preferences > General > Application and enable Show legacy unit tests.
- On the API Collection screen, click the Tests tab.
- In the sidebar, click New test suite.
Create a headers in response test
Now we can test if a header is returned in the response.
- Click New test and enter a name for the test, such as “Header in the body”.
- From the Select a request drop down, select the GET KongAir planned flights request.
- Enter the following JavaScript to check if there are any headers in the response:
const response1 = await insomnia.send(); expect(Object.keys(response1.headers).length).to.be.greaterThan(0); const body = JSON.parse(response1.data); const item = body[1]; expect(item).to.be.an('object'); - Click the Play icon next to the test. In the preview to the right, you should see that the test passes.
Cleanup
Clean up Insomnia
If you created a new collection and want to delete it, navigate to the collection, click it’s name in the sidebar on the right, and then select Delete.