Use variable expressions in test.each Jest

懵懂的女人 提交于 2021-02-04 19:14:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!