Pragmatic Testing in AdonisJS with Japa #4.1

Meet the API Client

In This Lesson

Learn how to use Japa's API Client for Functional Testing of AdonisJS routes. We'll install and register the plugin, and use the client in tests to make requests and assert against their responses.

Created by
@tomgobich
Published

Japa's API Client is structurally similar to Axios to work with, but is tailored toward testing and contains helpful assertions we can use to confirm expected behaviors.

First, though, we need to install and add this plugin to our Japa bootstrap file.

npm i -D @japa/api-client
Copied!
++import { apiClient } from "@japa/api-client";

export const plugins: Config["plugins"] = [
  assert(),
  apiClient(),
  pluginAdonisJS(app),
  disallowPinnedTests({
    disallow: !!process.env.CI,
  }),
];
Copied!
  • tests
  • bootstrap.ts

We can pass a baseURL option into the apiClient if needed, but this will default to the HOST and PORT, which is perfect for our use case, so we can leave this as-is.

This will add a client into our test context, and this client is the Axios-like API client we can use to test our routes. For example, if we send a get request to our home page, this should render the new app splashscreen that comes with a newly created AdonisJS project.

First, we'll make our first functional test, called api_client

node ace make:test api_client --site=functional
Copied!

Then, let's write a test to assert our splash screen is rendered.

test.group("Api client", () => {
  test("render the new app splashscreen on the home page", async ({
    client,
  }) => {
    const response = await client.get("/");

    response.assertOk();
    response.assertTextIncludes(
      "AdonisJS - A fully featured web framework for Node.js"
    );
  });
});
Copied!
  • assertOk ensures the response status was Ok (200)

  • assertTextIncludes ensures the HTML body text includes the provided string

If we were dealing with JSON, we can instead assert on the body, for example...

test("return hello world json response", async ({ client }) => {
  const response = await client.get("/json");

  response.assertOk();
  response.assertBody({
    hello: "world",
  });
});
Copied!

Now, assertBody will expect a one-to-one JSON body match. If we just need to check a part of the body, there's also assertBodyContains. If you take a look at the autocomplete options here as well, you can see there are assertions for just about everything you'd need to test against your response, which is fantastic.

Join the Discussion 0 comments

Create a free account to join in on the discussion
robot comment bubble

Be the first to comment!