【发布时间】:2019-03-28 07:31:36
【问题描述】:
当使用函数生成测试文件中经常使用的describe/it 块时,父级describe 中存在的beforeAll 或beforeEach 块将被忽略。
例如:
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);
});
在我正在处理的特定测试套件中(比这复杂得多,以防不明显) - 这样做会使事情变得非常棘手,并且使重用生成器函数非常具有挑战性。
有没有办法让beforeAll 或beforeEach 在函数内部生成的测试块之前运行,就像我原来的例子一样?
对于它的价值,在我上面的简单示例中设置 num 的等价物是 mount 使用 enzyme 的反应节点。
【问题讨论】:
-
我的感觉是,让它正常工作的唯一方法是在调用生成器之前让
beforeAll等效运行。但接下来的挑战是,如果有其他beforeEach以更高的描述运行,在我们的情况下 - 这似乎会导致问题......也许那里有一个不同的错误,我应该调查......
标签: unit-testing jasmine tdd jestjs enzyme