Pragmatic Testing in AdonisJS with Japa #2.2

Group & Test Lifecycle Hooks

In This Lesson

We'll walk through a number of lifecycle hooks we can use on a per-group and per-test basis. We'll also discuss how we can run a hook for each test and how setup hooks allow a convenient cleanup method.

Created by
@tomgobich
Published

Notes Used to Craft this Lesson

Now, lets say that instead of our counter's value persisting between each of our tests we instead wanted it to reset back to 0. For that, we have several options. We can do this on a per-test basis using setup and teardown.

Setup is run just before the test

test("increment the counter by one again", async ({ assert }) => {
  counter++;

  assert.equal(counter, 1);
}).setup(() => {
  counter = 0;
});
Copied!

Or, we can use teardown which is run just after the test.

test("increment the counter by one", async ({ assert }) => {
  counter++;

  assert.equal(counter, 1);
}).teardown(() => {
  counter = 0;
});
Copied!

These same methods are also available at the group level, the callback of the group here provides us the group instance that we can hook into.

test.group("State management", (group) => {
  let counter = 100;

  group.setup(() => {
    counter = 0;
  });

  // ...
});
Copied!

Note here though that this will only run before the entire group is started. If we wanted this to run before each test in the group, we can note that using each

test.group("State management", (group) => {
  let counter = 100;

  group.each.setup(() => {
    counter = 0;
  });

  // ...
});
Copied!

The setup hook also supports a cleanup function which is perfect if your setup needs to create state, we'd just return a function and it'll be called similar to the teardown hook

test.group("State management", (group) => {
  let counter = 100;

  group.each.setup(() => {
    counter = 0;

    return () => {
      counter = 100;
    };
  });

  // ...
});
Copied!

This is great when we need to keep logic together or access a variable that was directly created within the setup hook.

In terms of arguments for these hooks, the setup and teardown methods get an instance of the group or test class, depending on whether the hook is for the group or each test. The cleanup function gets whether the group or test failed as well as the group or test class.

Finally, to note, any of these methods can be asynchronous! So, if you need to perform any async operations, that is supported here.

Join the Discussion 0 comments

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

Be the first to comment!