What is an afterEach hook?
afterEach hook in the context of automated tests is a block of code that executes after all the tests in that spec file have run. Each spec file can have only one such afterEach hook.
When you are building automated tests you will encounter situations where you would be compelled to use the afterEach hook eg in the below scenarios:
Logout after each test so that the test user can log in fresh in subsequent test
Delete any data or resources created during the execution of the test
Logging any test-related information or data
**
afterEach() => {
// Teardown actions after each test
// Logging out of the application
// Cleaning up database
// Deleting the test user
});
***
Is it a good practice?
Should we go and implement afterEach hook in E2E test as it is made readily available by almost all the test frameworks 🤔
Now “Think” through the below scenarios:
One of your tests in a spec failed without completing its entire run
If you stop a test midway for some reason eg debugging
The script in the afterEach hook fails due to some error
In all of the above scenarios, the afterEach hook code would never execute and thus the very intention of implementing these afterEach hook fails!
How do you think we should implement such clean-up scripts? According to you what are the options?
Hope you find the article a useful resource. Do share your feedback with me at prashant@PristineProtech.com, visit www.PristineProtech.com to know more about our offerings and services...
Comments