如果我有这样的规范文件:
let a;
beforeEach(() => {
a = 'hello';
})
describe('my test suite', () => {
test.each([
[a, 'hello']
])(
'testing %s with expected result %s',
(myVariable, expectedResult) => {
expect(myVariable).toBe(expectedResult);
})
});
我收到一个错误 a
在参数化表中未定义。如果我使用常规 test
方法我可以访问 a
.
最佳答案
您确实忘记了 beforeEach() 行上的结束括号。
let a;
beforeEach(() => {
a = 'hello';
} );
您还有用于整数的 i% 和 %1,并且您需要字符串 (%s)。
只需一个测试,您就不需要 beforeEach() 并且可以简单地执行以下操作:
const a:string = 'hello';
test.each([[a, 'hello']])(
'.compare(%s, %s)',
(myVariable, expected) => {
expect(myVariable).toBe(expected);
},
);
但是,我也无法使其正常工作。我可以在测试中直接引用变量,比如:
const a:string = 'hello';
test.each([[a, 'hello']])(
'.compare(%s, %s)',
(myVariable, expected) => {
expect(a).toBe(expected);
},
);
使用您的 myVariable 不会从测试的闭环内部获取值。文字确实有效。 beforeEach 会破坏在那里设置值的目的,因为它不需要在 test.each() 中间进行更改,因为这意味着用不同的数据运行相同的测试。您仍然可以在您的 beforeEach 中创建对象和其他必需的东西,并直接引用它们(我的 a 变量),但是每次运行更改的测试数据似乎没有从外部循环中获取值。
关于javascript - 使用 Jest 的 test.each 参数化测试变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52996062/