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 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:
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.
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 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.
Copy
Ask AI
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()
Copy
Ask AI
pw.test("Response is ok", () => { pw.expect(pw.response.status).toBe(200);});
The tests will have passed once you click on the “Send” button.