Automated API testing ensures endpoints function as expected. Requestly allows you to write tests using JavaScript with the rq object enabling validations, schema checks, and automated workflows.
Common testing approaches include:
-
Contract Testing: Validate responses against JSON schemas.
-
Unit Testing: Test individual endpoints in isolation.
-
Error Handling: Verify API behavior for invalid inputs.
You can execute tests using either Pre-request scripts (run before a request is sent) or Post-response scripts (run after a response is received).
The Pre-request and Post-response tabs provide a scripting environment that allows dynamic behavior for API requests.
-
The Scripts → Pre-request tab enables processing before sending a request, such as setting variable values or modifying headers.
-
The Scripts → Post-response tab runs after receiving the response and allows for test assertions, logging, and response validation. This tab includes the Chai.js library, supporting behavior-driven development (BDD) syntax for test assertions.
Scripting Environment
Requestly provides a JavaScript runtime with built-in utilities. Here’s a quick reference table for key methods:
Writing Tests
To create a test, use the following syntax:
Example Tests
Status Code Check
JSON Body Validation
Schema Validation
Skipping Tests
Response specific assertions
The .to API is supported only for response data in Post-response scripts.
Status code assertions
.to.have assertions
Negation with .to.not
All the above assertions can be negated by inserting .not after .to:
.not.have.header() checks only that the header is absent. If you pass a
value as the second argument it is ignored, so
rq.response.to.not.have.header("Content-Type", "text/html") fails whenever
the header is present, whatever its value. To assert that a header exists but
holds a different value, compare it directly:
rq.expect(rq.response.headers.get("Content-Type")).to.not.equal("text/html").