Tests
Scripts
Hoppscotch lets you to add dynamic behaviour 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:
- Tests are executed after a response is received from the server
- You can add multiple tests to a request
- You can add tests to both requests saved and not saved in a collection
Hoppscotch will then execute the scripts after the response is received.
Post-request tests
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.
Writing post-request tests
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 recieved from APIs.
Examples
Let us look at some examples of how you can use Hoppscotch to write tests.
Test response status code
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() |
pw.test("Response is ok", () => {
pw.expect(pw.response.status).toBe(200);
});
The tests will have passed once you click on the "Send" button.
Assert response payload
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 type 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:
Scripts and the pw
API
Read more about the pw
APIs and it's documentation.