Pragmatic Testing in AdonisJS with Japa #1.2

Our First Test

In This Lesson

We'll write our first test with Japa and learn about spec files, as well as the three key components of crafting a good test: arrange, act, and assert.

Created by
@tomgobich
Published

Notes Used to Craft This Lesson

Tests are described within a specification, or spec, file. These specifications are often used to group tests by feature.

Take authentication, for example; you might have separate specifications for login, registration, and logout.

To create a spec file, we can easily use the Ace CLI, provided by AdonisJS.

node ace make:test assertions
Copied!

When we run this, it'll ask us which suite we want to place this test within. We'll use this to get comfortable with lightweight tests, so let's select 'unit'.

Once we run this, it'll create an assertions.spec.ts file within our tests/unit folder.

Inside this file, it'll start us with a test group for the spec and an actual empty test within the group.

A test is defined by calling the test function, and this function accepts two arguments. The first is the test name, and the second is a callback where we perform the test.

The goal of a test is to take something and make an assertion with it to confirm that something is what we expect. For example, we know that 2 + 2 is equal to 4, so we can assert that that should be the case. We can also change the name of this test to "my first test."

test("my first test", async ({ assert }) => {
  assert.equal(2 + 2, 4);
});
Copied!

We can then run our tests using the Ace CLI's node ace test command, and we'll see the output printed in our terminal the output.

The output here shows us the suite, spec, and name of the test, and a summary at the bottom of all the tests that were run. For each test, a green check means it passed, and a red x means it failed.

For example, if we switch this to expect 5 instead of 4, our assertion will fail, and we'll see that reflected as we run our tests!

Okay, let's put that back how we had it, so it passes again.

Lastly, there are three parts to a test:

  1. Arrange - this is where we perform setup work and get everything we need to do our test. This might include creating data, or in our simple test above, defining what numbers we'll be adding together.

  2. Act - this is where we perform the action we're testing. This is the actual addition of our two numbers.

  3. Assert - this is where we confirm our act step succeeded in its purpose, that our two numbers added to the sum we expected.

test("my first test", async ({ assert }) => {
  // 1. arrange
  const a = 2;
  const b = 4;

  // 2. act
  const result = a + b;

  // 3. assert
  assert.equal(result, 6);
});
Copied!

Join the Discussion 0 comments

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

Be the first to comment!