In many cases tests can share a common afterEach
clean-up even if it’s needed for one of them, as long as it doesn’t affect others.
Otherwise, this is what block structure is responsible for. One or several tests can be grouped with nested describe
just to have their own afterEach
, etc blocks, and the only downside is that it makes the report less pretty:
describe("a family of tests it makes sense to group together", () => {
...
describe("something I want to test", () => {
beforeEach(() => {
global.foo = "bar"
});
test("something I want to test", () => {
expect(myTest()).toBe(true)
}
afterEach(() => {
delete global.foo
});
});
beforeEach
and afterEach
can be desugared to try..finally
:
test("something I want to test", () => {
try {
global.foo = "bar"
expect(myTest()).toBe(true)
} finally {
delete global.foo
}
})
This also allows for asynchronous tests but requires them to be written with async
instead of done
.