Hooks
- 3 minutes to read
TestCafe Studio allows you to specify test actions that are executed before and after each test in a fixture. These action sequences are called test hooks (the before each and after each hook).
Hooks allow you to extract repetitive actions, like logging in or opening the tested view, and reuse them within the fixture.
Hooks include the same types of actions as the test body.
NOTE
The browsing context is preserved between hooks and the test body. If you switch the browsing context in the before each hook, the test starts in this context. The after each hook runs in the same browsing context that was used in the last test action.
Element selectors and functions are not shared between hooks and the test body.
Create a Hook
To create an empty hook, invoke the context menu for a fixture or .testcafe
file in the Explorer panel and click Add 'before each' hook or Add 'after each' hook:
This adds the before each or after each item to the fixture.
Add Actions to a Hook
You can move or copy actions from any test in the fixture to a hook. TestCafe Studio appends the selected actions to an existing hook or creates a new hook if none exists.
Alternatively, you can open the hook in the Test Editor and add actions from the Actions panel.
Move Actions From a Test
Select actions in the Test Editor (hold Cmd/Ctrl to select multiple actions) and click Move to 'before each' hook or Move to 'after each' hook on the toolbar.
This removes the selected actions from the test and adds them to the hook with the same parameters.
If you are moving actions that execute in an iframe, ensure that you pick the Switch to Iframe action as well.
Copy All Actions From a Test
To copy all actions from a test, invoke the context menu for this test in the Explorer panel and click Copy actions to 'before each' hook or Copy actions to 'after each' hook:
Add Actions in the Test Editor
You can open the hook in the Test Editor and add actions from the Actions panel.
Edit Hooks
Test hooks are displayed in the Explorer panel below a fixture name. Double-click before each or after each to open the hook.
You can also navigate to hooks when you edit tests. The Test Editor displays the before each and after each steps in each test whose fixture contains a hook. Click these steps to open the hook.
The Fixture Editor also displays the before each and after each items if this fixture has a corresponding hook.
Hooks are opened in the Test Editor. You can add actions from the Actions panel, modify action parameters, re-order, and delete actions.