在beforeEach()和afterEach()中获取Jest测试名称

时间:2020-05-06 17:01:41

标签: jestjs

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

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

3 个答案:

答案 0 :(得分:1)

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

Custom 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测试组运行一次​​。

答案 1 :(得分:0)

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

/** route: /task/get **/
public function yourTasksMethod(){ 

  //your code that retrieves your tasks

  return view('partial.tasks')->with('tasks', $tasks)->render();
}

此方法在expect.getState().currentTestName / beforeEach内部也适用

唯一的缺点是它还将包含当前描述部分的名称。 (根据您要执行的操作可能会很好。

它也不会为您提供您要求的时间信息。

答案 2 :(得分:0)

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

./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

相关问题