We'll learn how to validate AdonisJS API responses against an OpenAPI Specification, like those generated by Swagger APIs, using Japa's OpenAPI Assertions plugin.
If you're making an API and using something that generates an OpenAPI Specification for you, like Swagger, then Japa has a nifty plugin for you, called OpenAPI Assertions.
npm i -D @japa/openapi-assertions
Copied!
For this, we won't want to use Japa's API client to send the request; instead, we'll want to use axios, superagent, superset, request, or light-my-request. These are the responses supported by the @japa/openapi-assertions plugin. I'll go ahead and use axios here, and I'll install it as a normal dependency since I might not explicitly use it for testing.
npm i axios
Copied!
Next, we'll configure this within our plugins array, pointing the schemas option of the plugin to our OpenAPI Specification file. Within this project, I have a mock specification at ~/docs/openapi.json.
Next, for our test, we'll want to use axios (or one of the other supported packages) to send our request.
test("fetch a list of posts (openapi)", async ({ assert }) => { const response = await axios.get( `http://${env.get("HOST")}:${env.get("PORT")}/posts` );});
Copied!
We also need an absolute URL, which we can build using our HOST and PORT environment variables. If you have a lot of these, you can plot this into a variable or an env variable of its own.
The OpenAPI Assertions plugin has added a nifty isValidApiRespons method to our assert options.
test("fetch a list of posts (openapi)", async ({ assert }) => { const response = await axios.get( `http://${env.get("HOST")}:${env.get("PORT")}/posts` ); assert.isValidApiResponse(response);});
Copied!
All we have to do is pass our response directly into this function, and the plugin will do the rest! Within our project, we have this docs/openapi.json specification outlining rules for our endpoint. This plugin will read those rules and assert to confirm our response adheres to them. If it does, it'll succeed, and if it doesn't, it'll fail.