更新时间:2023-12-05 11:49:40
在许多情况下,测试可以共享一个常见的afterEach
清理,即使其中之一是必需的,只要它不影响其他清理即可.
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.
否则,这就是块结构所负责的.可以将一个或多个测试与嵌套的describe
分组,以拥有自己的afterEach
等块,唯一的缺点是它使报告不太美观:
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
和afterEach
可以还原为try..finally
:
test("something I want to test", () => {
try {
global.foo = "bar"
expect(myTest()).toBe(true)
} finally {
delete global.foo
}
})
这还允许进行异步测试,但要求它们使用async
而不是done
编写.
This also allows for asynchronous tests but requires them to be written with async
instead of done
.