Use Before, After, BeforeAll, and AfterAll Hooks
CucumberJS provides Before
, After
, BeforeAll
, AfterAll
hooks that you can customize to run custom code at specific points during test execution. These hooks are useful for setting up or cleaning up resources, logging, initializing test data, closing connections, or anything else that needs to happen before or after a test or test suite.
Work in Progress
Currently, you need to manually add your custom code in the hooks. Soon, you’ll be able to add hooks directly from the AI Recorder, making it easier to set up actions before or after your tests without writing any code.
Available Hooks
Hook | Runs When | Scope | Can Be Placed In |
---|---|---|---|
Before | Before each scenario | Scenario-level | Any .mjs in step-definitions |
After | After each scenario | Scenario-level | Any .mjs in step-definitions |
BeforeAll | Once before all scenarios in suite | Project-level | Any .mjs in step-definitions |
AfterAll | Once after all scenarios in suite | Project-level | Any .mjs in step-definitions |
Adding Test Hooks
To add hooks like Before
, After
, BeforeAll
, or AfterAll
, follow these steps.
NOTE
The example below shows how to add a Before
and After
hook. The flow is the same for all four types.
Go to the
features
folder, which contains all the scenarios you’ve created.Inside
features
, open thestep-definitions
folder. This contains.mjs
files where step logic is grouped.Example
your-project/ ├── features/ │ └── step-definitions/ │ ├── login.mjs │ └── checkout.mjs
Open any
.mjs
file in thestep-definitions
folder (for example,login.mjs
orcheckout.mjs
).Inside the file, add your desired hook (
Before
,After
,BeforeAll
, orAfterAll
) based on when you want your custom logic to run.Need help with the syntax?
Refer to the Examples section below to see how each hook is structured.
After making changes to the
.mjs
file, remember to push your changes to ensure they are applied during your tests.For detailed instructions, see Uploading the Modified Code.
Examples
Run logic before and after each scenario
Use the Before
and After
hooks to execute code before and after every scenario:
js
Before(async function () {
// Example: Initialize test context, navigate to a page, or log a message
console.log('Test is starting');
});
After(async function () {
// Example: Clean up test context or log completion
console.log('Test has run successfully');
});
Run logic before and after the entire test suite
Use the BeforeAll
and AfterAll
hooks to execute code once before the first scenario and once after the last scenario:
js
BeforeAll(async function () {
// Example: Set up global environment or start a service
console.log('Starting the test suite');
});
AfterAll(async function () {
// Example: Shut down service or close global resources
console.log('Finished running all scenarios');
});