【发布时间】: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");
});
})
更新 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