如果我有这样的规范文件:
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 中创建对象和其他需要的东西,并直接引用它们(我的一个变量),但是每次运行都会改变的测试数据似乎并没有从外部循环中获取值。
关于javascript - 使用 Jest 的 test.each 参数化测试变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52996062/