【问题标题】:Jest - Get Test and Description NameJest - 获取测试和描述名称
【发布时间】:2023-03-22 14:06:01
【问题描述】:

我正在尝试获取传递给it(name: string) Jest 函数的测试名称的名称,以及传递给describe(name: string, ....) 的描述名称。

有没有办法以某种方式访问​​它?

例如

describe("Description", () => {
  it("Test", () => {

    const description = "How do I get the description name?"
    const test = "How do I get the test name?";

    expect(`${description} - ${test}`).toBe("Description - Test");
  });
})

CodeSandbox Link

更新 1

我想要这个的根本原因是因为我想做一些基于描述、测试和一些环境变量(例如视口大小 + 模拟/真实数据)的自定义快照命名约定。

【问题讨论】:

  • 您打算如何使用它?您可以将其存储在闭包变量中,但不确定这是否能满足您的需求?但是,就描述块而言,使用实际的function () {} 而不是箭头函数,您可以调用this.description。例如,describe('hi', function () { console.log(this.description); }) 但是这不适用于 test/it 块。
  • 我想创建一个基于动态数据/环境变量以及测试+描述名称的快照命名辅助方法
  • 我也许可以使用expect.extend() 绑定this 并具有testPath: "/index.test.ts"currentTestName: "Description Test"
  • 欺骗How to get the current spec name,我刚刚在那边发布了一个新答案。

标签: javascript typescript jestjs


【解决方案1】:

您可以使用自定义匹配器实现此目的

expect.extend({
  testName(exp) {
      return {
          pass: this.currentTestName === exp,
          message: () => '',
      };
  },
});

describe("Description", () => {
  it("Test", () => {
      expect(`Description Test`).testName();
  });
});

【讨论】:

    【解决方案2】:

    也许,最明显的解决方案就是您想要的。无需将文字传递给describeit,只需将它们存储在相应的常量中,然后可以通过外部范围在相应的测试用例中轻松访问。

    这些常量可以很容易地通过环境变量中的值或文字默认值进行初始化。

    const suiteA = 'Description';
    describe(suiteA, () => {
      const testA = 'Test';
      it(testA, () => {
        expect(`${suiteA} - ${testA}`).toBe("Description - Test");
      });
    })
    

    【讨论】:

    • 是的,但是您必须为每个测试定义一个常量。有一个easier way
    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 2013-09-09
    • 2011-02-24
    • 2023-03-24
    • 2016-12-25
    相关资源
    最近更新 更多