Pragmatic Testing in AdonisJS with Japa #4.4

Asserting JSON Structures

In This Lesson

We'll learn how to test fetching a list of items functionally. Assert a successful response, confirm the body is as we expect, check object structures, and loosely validate response data.

Created by
@tomgobich
Published

Notes Used to Craft this Lesson

What about testing a list of items? For this, we have our posts.index that returns an array of 3 different posts.

export default class PostsController {
  // ...

  async index() {
    return [
      {
        id: 1,
        title: 'My first post',
        summary: 'Lorem ipsum dolor sit amet, consectetur ...',
      },
      {
        id: 2,
        title: 'My second post',
        summary: 'Lorem ipsum dolor sit amet, consectetur ...',
      },
      {
        id: 3,
        title: 'My third post',
        summary: 'Lorem ipsum dolor sit amet, consectetur ...',
      },
    ]
  }

  // ...
}
Copied!
  • app
  • controllers
  • posts_controller.ts

We'll test that this should "fetch a list of posts."

test("fetch a list of posts", async ({ client, assert, route }) => {
  const response = await client.get(route("posts.index"));

  response.assertOk();
});
Copied!

Beyond asserting our 'ok' response, we may also want to confirm that we received an array from our body. For this, we can grab the actual response body via response.body(), then utilize the isArray assertion to confirm it's an array.

test("fetch a list of posts", async ({ client, assert, route }) => {
  const response = await client.get(route("posts.index"));
  const body = response.body();

  response.assertOk();

  assert.isArray(body);
});
Copied!

Next, we may want to confirm the array of objects contains the properties we'd expect.

test("fetch a list of posts", async ({ client, assert, route }) => {
  const response = await client.get(route("posts.index"));
  const body = response.body();

  response.assertOk();

  assert.isArray(body);

  assert.properties(body.at(0), ["id", "title", "summary"]);
});
Copied!

Lastly, assertBodyContains also works great with arrays! So, we can use that to loosely confirm that the actual data we received is correct as well.

test("fetch a list of posts", async ({ client, assert, route }) => {
  const response = await client.get(route("posts.index"));
  const body = response.body();

  response.assertOk();

  assert.isArray(body);

  assert.properties(body.at(0), ["id", "title", "summary"]);

  response.assertBodyContains([
    { id: 1, title: "My first post" },
    { id: 2, title: "My second post" },
    { id: 3, title: "My third post" },
  ]);
});
Copied!

Join the Discussion 0 comments

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

Be the first to comment!