问题
Below is my code snippet:
describe('Upper Describe,()=>{
let value;
beforeEach(()=>{
value=require('testModule').value;
});
it.each([
`${value}`,
])('test something',(value)=>{
console.log(value);
});
});
Here the value
comes to be undefined
.
My guess is it is because as the describe blocks get loaded at the starting so are the values for it.each
. Can anyone please help me with a workaround to get the variable values inside it.each array?
Thanks in advance!!
回答1:
Instead of passing the value itself to it.each
pass a function that returns the value.
This will delay evaluation of the value so beforeEach
can modify what gets returned:
describe('Upper Describe', () => {
let value;
beforeEach(() => {
value = require('testModule').value;
});
it.each([
() => `${value}`, // pass a function that returns the value
])('test something', (func) => {
console.log(func()); // SUCCESS: prints value export from testModule
});
});
来源:https://stackoverflow.com/questions/52512309/use-variable-expressions-in-test-each-jest