Test an API status code and response body
Check the status code and the fields of the result in one zriz pipeline. A test that reads only the status code misses a wrong body.
The problem
An API can answer 201 and send a wrong body. A field is absent, or it holds the data of a different user. A test that reads only the status code passes, and the client breaks.
The test
The example is a shop API. POST /api/auth/register makes a user and answers 201 with a token.
Start from a project that zz init made: the quick start gives the commands. Add the action register to the resource file. Keep the action check as it is.
.zriz/resources/target.json:
{
"type": "http",
"description": "Your app under test",
"base-url": "${env.TARGET_URL}",
"headers": { "Content-Type": "application/json" },
"actions": {
"check": { "method": "GET", "path": "/api/health" },
"register": { "method": "POST", "path": "/api/auth/register" }
}
}
.zriz/pipelines/register-reply.json:
{
"description": "Sign up: check the status code and the body",
"steps": [
{ "set": { "email": "u-${gen.uuid}@test.com" } },
{
"call": "target/register",
"body": { "email": "${ctx.email}", "password": "secret123", "name": "Ann" },
"expect": [
["status", "==", 201],
["body.email", "==", "${ctx.email}"],
["body.name", "==", "Ann"],
["body.user_id", "not-empty"],
["body.token", "not-empty"]
]
}
]
}
Run it
zz run register-reply
"status":"pass"
What it proves
status == 201: the API made the user. A200or a500fails the test.body.email == ${ctx.email}: the result has the e-mail that the test sent, not a different one.body.name == Ann: the API stored the name.not-emptyonbody.user_idandbody.token: the client gets the id and the token that it needs.
Common mistake: A fixed e-mail passes one time, then fails as a duplicate.
${gen.uuid}makes a new e-mail for each run.
Next
- Test that a bad request returns 400
- Pipelines lists each operator of a check.