Return cleanup functions from beforeAll and beforeEach
See original GitHub issue🚀 Feature Proposal
It would be a nice addition if the beforeAll()
and beforeEach()
function could return cleanup functions. This is based on the cleanup function of React.useEffect()
.
Because one setup may depend on another, the cleanup functions should run in the reverse order of their definition after the afterAll()
and afterEach()
blocks respectively. I.e. the following test:
afterAll(() => {
console.log(1);
});
beforeAll(() => {
console.log(2);
return () => {
console.log(3);
};
});
afterAll(() => {
console.log(4);
});
beforeAll(() => {
console.log(5);
return () => {
console.log(6);
};
});
afterAll(() => {
console.log(7);
});
it('', () => {
console.log('test');
});
will log:
2
5
test
1
4
7
6
3
Motivation
Currently one needs to store the variables on a higher scope, so the cleanup can be done in a afterAll()
or afterEach()
block. This works fine, but it’s more work. One needs to declare the variables and possibly explicitly add type definitions. Also returning such cleanup functions keeps related setup and cleanup close together.
Example
Currently:
import { Sequelize } from 'sequelize-typescript';
import { User } from '../models';
import { setupDB } from '../utils';
let db: Sequelize;
beforeAll(async () => {
db = await setupDB();
});
afterAll(async () =>
await db.close();
});
it('should create a user', async () => {
await User.create({ name: 'Me' });
});
With returned cleanup functions.
import { User } from '../models';
import { setupDB } from '../utils';
beforeAll(async () => {
const db = await setupDB();
return () => db.close();
});
it('should create a user', async () => {
await User.create({ name: 'Me' });
});
Variables can still be assigned for use in other setup blocks or tests
import { Sequelize } from 'sequelize-typescript';
import { User } from '../models';
import { setupDB } from '../utils';
let db: Sequelize
beforeAll(async () => {
db = await setupDB();
return () => db.close();
});
afterEach(async () => {
await db.truncate()
});
it('should create a user', async () => {
await User.create({ name: 'Me' });
});
Pitch
This changes the behaviour of beforeAll()
and beforeEach()
.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:5 (1 by maintainers)
Top GitHub Comments
I have given the @jeysal’s some thought. I like this as well, but I don’t like the idea of having to use
.current
in every test to access the wanted value. This might even be a source of confusion for some users.Of course one could still the following, even if the hook would return a fixture ref.
I do like the idea of using a new name for the hook, i.e.
aroundEach
orsetupEach
.This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.