【问题标题】:Get Jest test name within beforeEach() and afterEach()在 beforeEach() 和 afterEach() 中获取 Jest 测试名称
【发布时间】:2021-06-27 04:17:21
【问题描述】:

我正在运行 Jest,并尝试记录每个测试的开始和结束时间戳。我试图将我的时间戳日志记录在 beforeEach()afterEach() 块中。如何在 beforeEach()afterEach() 块中记录我的 Jest 测试的名称?

另外,是否有更全局的方式在不使用beforeEach()afterEach() 的情况下记录所有测试前后的测试名称和时间戳?

【问题讨论】:

  • 第二个问题,你考虑过beforeAllafterAll吗?
  • @Dario - 对不起,我应该更清楚。我的意思是获得一些全局方式来记录每个测试的名称和时间戳。不幸的是,Jest 在beforeAll()afterAll() 中没有这些信息。

标签: jestjs


【解决方案1】:

您可以像这样开玩笑地访问当前测试的名称:

expect.getState().currentTestName

此方法也适用于beforeEach / afterEach

唯一的缺点是它还会包含您当前描述部分的名称。 (这可能没问题,具体取决于您要执行的操作。

它也没有给你你要求的时间信息。

【讨论】:

    【解决方案2】:

    beforeEach 中没有关于当前运行测试的信息。与 Jasmine 类似,套件对象在 Jest 中作为describe 函数中的this 上下文可用,可以修补规范定义以公开所需的数据。更简单的方法是为拦截测试名称的全局 it 定义自定义包装函数。

    Custom reporter 是一种更好的方法。 Reporter界面是自记录的,必要的数据是available in testResult

    性能测量已经可用:

    module.exports = class TimeReporter {
      onTestResult(test, testResult, aggregatedResult) {
        for (let { title, duration } of testResult.testResults)
            console.log(`test '${title}': ${duration} ms`);
      }
    }
    

    可以这样使用:

    reporters: ['default', "<rootDir>/time-reporter.js"]
    

    如前所述,有beforeAllafterAll,它们每个describe 测试组运行一次​​。

    【讨论】:

    • 使用记者正是我想要的。我正在使用最新版本的 Jest (26.0.1),但在 testResult.testResults 中看不到 startTimeendTime。我需要使用特定版本的 Jest 吗?我在testResult.testResults 中看到了{ancestorTitles, duration, failureMessages, fullName, numPassingAsserts, status, title}
    • 感谢您的关注。看来我检查了不同的类型。它目前保持不变。开始和结束时间以 testResult.perfStats 的形式提供,以备您单独需要时使用。
    • 不客气。不幸的是,testResult.perfStats 没有细分每个测试的开始和结束时间。
    【解决方案3】:

    您可以设置测试环境并直接记录时间或将名称和时间信息写入仅在相关测试中可用的全局变量:

    ./tests/testEnvironment.js

    const NodeEnvironment = require('jest-environment-node');
    
    class TestEnvironment extends NodeEnvironment {
        constructor(config, context) {
            super(config, context);
        }
    
        async setup() {
            await super.setup();
        }
    
        async teardown() {
            await super.teardown();
        }
    
        async handleTestEvent(event, state) {
            if (event.name === 'test_start') {
                // Log things when the test starts
            } else if (event.name === 'test_done') {
                console.log(event.test.name);
                console.log(event.test.startedAt);
                console.log(event.test.duration);
                this.global.someVar = 'set up vars that are available as globals inside the tests';
            }
        }
    
    }
    
    module.exports = TestEnvironment;
    

    对于每个测试套件,需要以下注释才能使用此环境:

    /**
     * @jest-environment ./tests/testEnvironment
     */
    

    另见https://jestjs.io/docs/configuration#testenvironment-string

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多