Javascript 笑话:如何在(仅仅)一次单独的测试后拆卸
Javascript 笑话:如何在(仅仅)一次单独的测试后拆卸,javascript,testing,jestjs,teardown,Javascript,Testing,Jestjs,Teardown,jest提供了afterEach、beforeach、aftereall和beforeAll来完成设置和拆卸逻辑。我想做的是,在一次特定的测试后进行清理。考虑以下事项: describe("a family of tests it makes sense to group together", () => { ... test("something I want to test", () => { // some
jest
提供了afterEach
、beforeach
、aftereall
和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
。这意味着随后的所有测试都可能失败。我看到的不是一个测试失败,而是一大堆测试失败,这可能会让人困惑
势(非理想)解
一种解决方案是在每次之后将delete global.foo
添加到我的中。其实并不需要在每次测试后都运行它,但它也不会造成任何伤害。另一个解决方案是将特定测试单独放置,这样每次之后的将只应用于它。但这似乎也不理想——如果该测试属于其他测试,那么它也不可能保留在其他测试中
我的问题:
是否有一种方法可以只为特定测试运行拆卸逻辑(而不在实际测试中运行它)。在我的特定用例中,第一个概述的解决方案很好,但我可以想象,在某些情况下,可能需要更细粒度的控制。例如,如果我的拆卸方法花费了很长时间,我就不想重复很多次,因为这会降低整个测试套件的速度。在许多情况下,测试可以在每次清理后共享一个通用的,即使其中一个需要,只要不影响其他测试
否则,这就是块结构所负责的。一个或多个测试可以与嵌套的descripe
一起分组,以便在每个等块之后都有自己的,唯一的缺点是它会降低报告的美观性:
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
});
});
每次之前
和每次之后
都可以被删除到try.。最后
:
test("something I want to test", () => {
try {
global.foo = "bar"
expect(myTest()).toBe(true)
} finally {
delete global.foo
}
})
这也允许异步测试,但要求使用async
而不是done
编写异步测试。我发现嵌套描述方法比try更好。finally block是因为当finally块中的代码失败时测试失败,但当afterEach或afterAll中的代码失败时测试仍然可以通过。