Scripts
Postdata 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
Postdata 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
Postdata ships a powerful API calledpw
which can handle post-request scripts as well as tests. Here we’ll use pw
to run tests on the response received from APIs.
Examples
Let us look at some examples of how you can use Postdata 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.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() |
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.toBe()
to assert specific values and .toBeType()
to assert specific data types as shown in the code snippet below: