【问题标题】:jest: How to teardown after (just) an individual test笑话:如何在(仅)一个单独的测试后拆解
【发布时间】:2020-07-17 16:16:55
【问题描述】:

jest 提供afterEachbeforeEachafterAllbeforeAll 来完成设置和拆卸逻辑。我想做的是在一项特定测试后进行清理。考虑以下几点:

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 仅适用于它。但这似乎也不理想 - 如果该测试属于其他测试,则它可能会保留在它们身上。

我的问题:

有没有办法只为特定测试运行拆解逻辑(而不在实际测试中运行它)。在我的特定用例中,第一个概述的解决方案很好,但我可以想象可能存在需要更细粒度控制的情况。例如,如果我的拆卸方法需要很长时间,我不想重复很多次,因为这会减慢整个测试套件的速度。

【问题讨论】:

    标签: javascript testing jestjs teardown


    【解决方案1】:

    在许多情况下,测试可以共享一个公共的afterEach 清理,即使其中一个需要它,只要它不影响其他测试。

    否则,这是块结构负责的。一个或多个测试可以与嵌套的describe 分组,只是为了拥有自己的afterEach 等块,唯一的缺点是它使报告不太美观:

    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
            });
        });
    

    beforeEachafterEach 可以脱糖为try..finally

    test("something I want to test", () => {
        try {
            global.foo = "bar"
            
            expect(myTest()).toBe(true)
        } finally {
            delete global.foo
        }
    })
    

    这也允许异步测试,但需要使用async 而不是done 编写。

    【讨论】:

    • 我发现嵌套 describe 方法比 try..finally 块更好,因为当 finally 块中的代码失败时测试失败,但当 afterEach 或 afterAll 中的代码失败时测试仍然可以通过。
    猜你喜欢
    • 2020-11-12
    • 2019-07-21
    • 2019-08-03
    • 2018-10-19
    • 2018-12-23
    • 2018-03-23
    • 2021-12-22
    • 2015-10-17
    • 2018-12-19
    相关资源
    最近更新 更多