且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

开玩笑:(仅)单个测试后如何拆卸

更新时间: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
        });
    });

beforeEachafterEach可以还原为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.