簡體   English   中英

笑話:如何在(僅)一個單獨的測試后拆解

[英]jest: How to teardown after (just) an individual test

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僅適用於它。 但這似乎也不理想——如果該測試屬於其他測試,那么它可能會保留在它們身上。

我的問題:

有沒有辦法只為特定測試運行拆解邏輯(而不在實際測試中運行它)。 在我的特定用例中,第一個概述的解決方案很好,但我可以想象可能存在需要更細粒度控制的情況。 例如,如果我的拆卸方法需要很長時間,我不想重復很多,因為這會減慢整個測試套件的速度。

在許多情況下,測試可以共享一個共同的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編寫它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM