use*_*er1 9 arrays jasmine jestjs ts-jest
describe("SuiteName", () => {
var numberArray =[1,2,3];
beforeEach(async () => {
//I want 'n' from test in this before each method
console.log("Before Each" + expect.getState().currentTestName + 'number ' + n);
});
test.each(numberArray)("Tesst Name" , async (n) => {
console.log("Current parameter is-> " + n);
});
});
Run Code Online (Sandbox Code Playgroud)
你好,我是 Jest 的新手,想了解如何获取 beforeeach 块中的数值?
通过查看笑话代码(文档没有多大帮助),似乎传递给 beforeEach 的回调是使用 done 回调参数调用的,这没有帮助。(来源https://github.com/facebook/jest/blob/0e50f7313837bd005a560cb2161423ab06845733/packages/jest-circus/src/run.ts和https://github.com/facebook/jest/blob/66629be6194f5e107a26f406180a6ed597fb3c5 5/包/笑话-马戏团/src/utils.ts )
但这并不重要,因为在描述中 beforeEach 和测试共享相同的范围,并且在测试套件中,测试按顺序运行(没有对 testState 的重叠“并发”访问),因此这样做完全没问题:
describe("SuiteName", () => {
const testState = { n: undefined };
var numberArray =[1,2,3];
beforeEach(async () => {
//I want 'n' from test in this before each method
console.log("Before Each" + expect.getState().currentTestName + 'number ' + testState.n);
});
numberArray.forEach(n => {
console.log("Current parameter is-> " + n);
testState.n = n;
test('Tesst Name for n: ' + n, async () => {
console.log("Current parameter is-> " + n);
})
});
});
Run Code Online (Sandbox Code Playgroud)
问题是,通过将 test.each 拆分为共享相同代码的多个测试,您失去了 test.each 的一些好处。但使用 test.each 似乎没有办法解决这个问题。
或者,由于 test.each 和 beforeEach 的用例都可以防止重复代码并使测试更具可读性,为什么不将 beforeEach (异步)挂钩代码与实际测试链接起来:
describe("SuiteName", () => {
var numberArray =[1,2,3];
const forgetBeforeEachWeAreDoingTestEach = (n) => {
return new Promise((resolve) => {
//I want 'n' from test in this before each method
console.log("Before Each" + expect.getState().currentTestName + 'number ' + n);
resolve();
});
});
test.each(numberArray)('Tesst Name', async (n) => {
forgetBeforeEachWeAreDoingTestEach(n).then(() => {
console.log("Current parameter is-> " + n);
});
});
});
Run Code Online (Sandbox Code Playgroud)
我用 Promise 完成了上述操作,因为我是老派,但大多数时候从一种到另一种的转换非常简单
可能只是:
await forgetBeforeEachWeAreDoingTestEach(n);
console.log("Current parameter is-> " + n);
Run Code Online (Sandbox Code Playgroud)
注意:
这里之前的 stackoverflow 答案提供了与 sinon.sandbox 的第一个(testState)类似的解决方案,但没有解决问题test.each(使用多个参数进行 1 个测试 VS 使用相同代码进行多个测试)
| 归档时间: |
|
| 查看次数: |
12588 次 |
| 最近记录: |