在 test.each Jest 中使用变量表达式 [英] Use variable expressions in test.each Jest

查看:21
本文介绍了在 test.each Jest 中使用变量表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码片段:

describe('Upper Describe,()=>{
  let value;
  beforeEach(()=>{
    value=require('testModule').value;
  });

  it.each([
    `${value}`,
  ])('test something',(value)=>{
    console.log(value);
  });
});

这里的 value 变成了 undefined.

我的猜测是因为随着描述块在开始时被加载,it.each 的值也是如此.任何人都可以帮我解决方法来获取 it.each 数组中的变量值吗?

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?

提前致谢!!

推荐答案

不是将值本身传递给 it.each,而是传递一个返回值的函数.

Instead of passing the value itself to it.each pass a function that returns the value.

这将延迟对值的评估,以便 beforeEach 可以修改返回的内容:

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
  });
});

这篇关于在 test.each Jest 中使用变量表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆