What is a good and clean way to cleanup after a test case failed? For a lot of test cases, I first create a clean database environment, which needs to be cleaned up after a test case finishes.
test('some test', async () => {
const { sheetService, cleanup } = await makeUniqueTestSheetService();
// do tests with expect()
await cleanup();
});
Problem is: If one of the expects
fails, cleanup()
is not invoked and thus the database environment is not cleaned up and jest complains Jest did not exit one second after the test run has completed.
because the connection is not closed.
My current workaround looks like this, but it doesn't feel good and clean to push the cleanup hooks to an array which than is handled in the afterAll
event.
const cleanUpHooks: (() => Promise<void>)[] = [];
afterAll(async () => {
await Promise.all(cleanUpHooks.map(hook => hook()));
});
test('some test', async () => {
const { sheetService, cleanup } = await makeUniqueTestSheetService();
// do tests with expect()
await cleanup();
});
afterEach
execution for unit tests because I want them isolated to also been able to run them in parallel to decrease the time spent in the process. If you don't need that level of isolation, restoring the database in theafterAll
execution it seems enough clean from my point of view. – SelfimportantafterEach
? In my case it would be the database connection. – Flophousecleanup
function does), even if a test case fails ;) – FlophousebeforeEach
and the test cases for the database connection reference, which can lead to some unexpected fails when executed in parallel, right? – Flophouse