gpt4 book ai didi

jasmine - AfterEach 和 BeforeEach 仅用于描述()

转载 作者:行者123 更新时间:2023-12-02 18:02:03 24 4
gpt4 key购买 nike

我有这个演示代码。

describe('demo', () => {
beforeEach( async () => {
console.log('->before each')
})

afterEach( async () => {
console.log('->after each')
})

describe('->1', () => {
it('->1.1', async () => {
console.log('->1.1')
})

it('->1.2', async () => {
console.log('->1.2')
})
})

describe('->2', () => {
it('->2.1', async () => {
console.log('->2.1')
})

it('->2.2', async () => {
console.log('->2.2')
})
})
})

我正在等待这个结果:

->before each
->1
->1.1
->1.2
->after each
->before each
->2
->2.1
->2.2
->after each

我希望 afterEach 和 beforeEach 仅在 describe() 之前和之后运行,而不是 it() 之前和之后运行。

实际工作原理:

->1
->before each
->1.1
->after each
->before each
->1.2
->after each

->2
->before each
->2.1
->after each
->before each
->2.2
->after each

我认为 afterEach 和 beforeEach 只在同一级别运行,而不是在 children 中运行。

谢谢!

最佳答案

是的,不幸的是,beforeEach()afterEach() 为每个 it() block 运行。但是您可以使用 beforeAll()afterAll() 来重构您的测试,如下所示:

describe('demo', () => {

describe('->1', () => {
beforeAll(async () => {
console.log('beforeAll');
});

afterAll(async () => {
console.log('afterAll');
});

it('->1.1', async () => {
console.log('->1.1');
});

it('->1.2', async () => {
console.log('->1.2');
});
});

describe('->2', () => {
beforeAll(async () => {
console.log('beforeAll');
});

afterAll(async () => {
console.log('afterAll');
});
it('->2.1', async () => {
console.log('->2.1');
});

it('->2.2', async () => {
console.log('->2.2');
});
});
});

输出

->beforeAll
->1
->1.1
->1.2
->afterAll
->beforeAll
->2
->2.1
->2.2
->afterAll

这为您提供了预期的结果,但您必须编写更多代码。但在测试中,有一些冗余代码是可以的。

关于jasmine - AfterEach 和 BeforeEach 仅用于描述(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51534192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com