Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable expressions in test.each Jest

Tags:

jestjs

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!!

like image 988
amal Avatar asked Oct 15 '25 23:10

amal


1 Answers

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
  });
});
like image 145
Brian Adams Avatar answered Oct 18 '25 08:10

Brian Adams