documentation/getting-started/rest/tests.mdx
Hoppscotch lets you add dynamic behavior to REST requests. This allows you to write test suites and build requests that can contain dynamic parameters. You can add JavaScript code that executes at two events in the flow:
<Tip>Hoppscotch will then execute the scripts after the response is received.</Tip>
As you introduce new code, tests ensure that your API is working as intended. The higher your test coverage, the more flexible and bug-resistant your code will be. You'll be spending less time wondering why deleting a picture of a coconut breaks your code.
Hoppscotch ships a powerful API called pw which can handle post-request scripts as well as tests. Here we'll use pw to run tests on the response received from APIs.
Let us look at some examples of how you can use Hoppscotch to write tests.
Let us write a test to check whether the response to our request has a status code of 200. Which means that there are no errors in the response body. We'll use the below URL with the GET method.
https://www.httpbin.org/status/200
In this case, we'll need to write two expect statements one for checking the status and another for checking the response body. However, we can wrap expect statements with the test method from the pw API to group related statements.
There are two ways to test the status code:
| Condition | Code |
|---|---|
Check if response code is 200 | pw.expect(pw.response.status).toBe(200) |
| In-built matcher function | pw.expect(pw.response.status).toBeLevel2xx() |
The tests will have passed once you click on the "Send" button.
In this example, we test whether a user id points to a particular user. Let us use the following GET API endpoint
https://reqres.in/api/users/10
We will use .toBe() to assert specific values and .toBeType() to assert specific data types as shown in the code snippet below:
pw.test("Check first name", () => {
const user = pw.response.body.data;
pw.expect(user.first_name).toBe("Byron");
pw.expect(user.first_name).toBeType("string");
});
Running the test will produce the result as shown below:
{
"data": {
"id": 10,
"email": "[email protected]",
"first_name": "Byron",
"last_name": "Fields",
"avatar": "https://reqres.in/img/faces/10-image.jpg"
},
"support": {
"url": "https://contentcaddy.io?utm_source=reqres&utm_medium=json&utm_campaign=referral",
"text": "Tired of writing endless social media content? Let Content Caddy generate it for you."
}
}