首页 > 解决方案 > 有没有办法在 jest hooks 中获取测试的文件名?

问题描述

基于https://jestjs.io/docs/en/configuration#testenvironment-string,在我的 jest 配置中我有 "testEnvironment": "<rootDir>/scripts/testEnvironment.js". 此 testEnvironment.js 文件包含具有 setup()、teardown() 和 handleTestEvent() 方法的自定义类。

有什么方法可以从一个玩笑的钩子中获取文件名,比如run_describe_starttest_start或者其他什么?

标签: typescriptjestjs

解决方案


如同一参考部分所示,环境类接收测试文件的完整路径:

class CustomEnvironment extends NodeEnvironment {
  constructor(config, context) {
    super(config, context);
    this.testPath = context.testPath;
    ...
}

文件名可以提取为

this.testFile = path.basename(this.testPath);

当在构造函数中赋值时,它在其他方法中可用。


推荐阅读