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.
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.
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
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
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.