gpt4 book ai didi

unit-testing - 在 Jest 中,当使用函数生成 describe/it block 时,有没有办法让 beforeAll/beforeEach block 在断言之前运行?

转载 作者:行者123 更新时间:2023-12-04 15:53:20 24 4
gpt4 key购买 nike

当使用函数生成测试文件中经常使用的describe/it block 时,beforeAllbeforeEach 存在于父 describe 中的 block 将被忽略。

例如:

const repeatedTests = (num) => {
// DOES NOT WORK - num is undefined
describe(`Testing number ${num}`, () => {
it('should exist', () => {
expect(num).toBeDefined();
});
it('should be a number', () => {
expect(num).not.toBeNaN();
});
it('should be less than 5', () => {
expect(num).toBeLessThan(5);
});
});
};

describe.each([[1],[2],[3]])('Describe for %i', (num) => {
let numForTesting;
beforeAll(() => {
numForTesting = num;
});
repeatedTests(numForTesting);
});

我理解为什么会这样 - repeatedTests 将立即运行,因为测试运行器不是 describe/it当心。

为了让它工作,我需要做这样的事情:

const repeatedTests = (num) => {
describe(`Testing number ${num}`, () => {
let numForTesting;
beforeAll(() => {
numForTesting = num;
});
it('should exist', () => {
expect(numForTesting).toBeDefined();
});
it('should be a number', () => {
expect(numForTesting).not.toBeNaN();
});
it('should be less than 5', () => {
expect(numForTesting).toBeLessThan(5);
});
});
};

describe.each([[1],[2],[3]])('Describe for %i', (num) => {
repeatedTests(num);
});

在我正在处理的特定测试套件中(它比这复杂得多,如果不是很明显的话)- 以这种方式做事会使事情变得非常棘手,并且使生成器函数的重用变得非常具有挑战性。

有没有办法让 beforeAllbeforeEach 在函数内部生成的测试 block 之前运行,就像我原来的例子一样?

就其值(value)而言,在我上面的简单示例中设置 num 相当于使用 enzymemount react 节点。

最佳答案

Is there any way to have a beforeAll or beforeEach run before a testing block that's generated inside of a function, a la my original example?

鉴于您提到的原因,我的感觉是答案是否定的。

这是一种可能满足您需要的不同方法。它使用 generateState 函数而不是 jest hook。

const repeatedTests = (generateState) => {

const num = generateState();

describe(`Testing number ${num}`, () => {
it('should exist', () => {
expect(num).toBeDefined();
});
it('should be a number', () => {
expect(num).not.toBeNaN();
});
it('should be less than 5', () => {
expect(num).toBeLessThan(5);
});
});
};

describe.each([[1], [2], [3]])('Describe for %i', (num) => {

const generateState = () => {
return num;
}

repeatedTests(generateState);
});

这是测试输出:

 PASS  ./index.test.js
Describe for 1
Testing number 1
√ should exist (4ms)
√ should be a number (1ms)
√ should be less than 5
Describe for 2
Testing number 2
√ should exist
√ should be a number
√ should be less than 5 (1ms)
Describe for 3
Testing number 3
√ should exist
√ should be a number (1ms)
√ should be less than 5

关于unit-testing - 在 Jest 中,当使用函数生成 describe/it block 时,有没有办法让 beforeAll/beforeEach block 在断言之前运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52959586/

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