Dynamic hook (afterThis) to enable clean-up during test.
See original GitHub issue🚀 Feature Proposal
During (integration) testing I generally have to prepare a lot of pre-conditions for a specific test and clean them up after. If I use the afterEach
hook to run my cleanup (like delete all created users) then it blocks me from running my tests in parallel since it might delete users who are still being used by other tests.
It would be nice to have a afterThis
hook which I can use inside my test to trigger clean-up when this particular test completes. This would work very similarly to golang’s defer
which is an amazing tool during tests.
Example
describe('UsersAPI', () => {
it('allows only admin users access', async () => {
const nonAdminUser = createUser({admin: false}); // custom test utility
afterThis(() => deleteUser(nonAdminUser.id)); // example of hook usage
const adminUser = createUser({admin: true});
afterThis(() => deleteUser(adminUser.id));
// todo: do the actual tests and assertions
});
});
Pitch
Since this functionality would be part of the core I don’t really see how someone could add this as elegantly as an external library/plugin. However, having this hook in jest would allow us to elegantly write tests which can embrace the parallel power of nodejs. Having a lot of tests is good, but running them faster is better!
Issue Analytics
- State:
- Created 4 years ago
- Reactions:10
- Comments:6 (2 by maintainers)
Top GitHub Comments
For 3 reasons:
afterThis
hook into thecreateUser
helper function, then I would never even have to think about cleanup in my test. Any helper function which creates resources will be responsible for cleaning them up too.Yeah, something like this would be great, but we would need some API to bind it to a single test. Need to think about this, but some sort of
test.modern
,test.strict
, test.boundor some such is high on my list of wanted features. Might spend some time once v28 is released trying to design something and gather feedback. In addition to bound setups and cleanups I'd like to add a bound
expect` so we can properly count assertions and tell you how far you got