jest
提供afterEach
、beforeEach
和来完成设置afterAll
和beforeAll
拆卸逻辑。我想做的是在一项特定测试后进行清理。考虑以下:
describe("a family of tests it makes sense to group together", () => {
...
test("something I want to test", () => {
// some setup needed for just this test
global.foo = "bar"
// the test
expect(myTest()).toBe(true)
// clear up
delete global.foo
}
...
}
上面的问题...
如果上面的测试由于某种原因失败,则delete global.foo
永远不会运行。这意味着它之后的所有测试都可能失败。我没有看到 1 个测试失败,而是看到一大堆测试失败,这可能会令人困惑。
潜在(非理想)解决方案
一种解决方案就是添加delete global.foo
到我的afterEach
. 它实际上并不需要在每次测试后运行,但它也不会造成任何伤害。另一种解决方案是将特定测试单独放置,以便afterEach
仅适用于它。但这似乎也不理想——如果该测试属于其他测试,那么它可能会保留在它们身上。
我的问题:
有没有办法只为特定测试运行拆解逻辑(而不在实际测试中运行它)。在我的特定用例中,第一个概述的解决方案很好,但我可以想象可能存在需要更细粒度控制的情况。例如,如果我的拆卸方法需要很长时间,我不想重复很多,因为这会减慢整个测试套件的速度。