Get the current test/spec name in Jest

依然范特西╮ 提交于 2020-08-19 12:25:34

问题


Is there a way to get the current spec name from within the running test?

Basically I want to save a file, eg. using a function saveFile(), with the name of the file being the spec name. Without having to manually retype the name of the test.


回答1:


I found that the only possible way was through the use of expect(), which contains the spec name in its this. doing something like

expect.extend({
  async toSaveFile(data) {
    fs.writeFileSync(`${this.currentTestName}.txt`, data)
    return { pass: true };
  },
});

allows to then do

expect().toSaveFile('contents of the file');

it's definitely a hack, but it's the only way I could find to get a reference to the spec name. there is also this.testPath that indicates the test file




回答2:


This worked for me

console.log(expect.getState().currentTestName);



回答3:


Not sure how @Giacomo concluded that was "the only possible" way :) since there's this alternative mentioned in this GitHub issue, which makes the test name accessible directly in the test via jasmine['currentTest'].fullName, no extend needed.

jest.config.js:

module.exports = {
    setupFilesAfterEnv: ['./jest.setup.js'],
    
    .................
};

jest.setup.js:

// Patch tests to include their own name
jasmine.getEnv().addReporter({
    specStarted: result => jasmine.currentTest = result,
    specDone: result => jasmine.currentTest = result,
});

Then, in your *.test.js files...

describe('Test description', () => {
    beforeEach(() => console.log('Before test', jasmine['currentTest'].fullName));

    test(...);
});


来源:https://stackoverflow.com/questions/52788380/get-the-current-test-spec-name-in-jest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!