Get the current test/spec name in Jest

This worked for me

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

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


There's been a 2+-year old issue in the Jest repo to make the test name available, with no official solution as of Feb 2021. One core maintainer said none would be available any time soon.

The community has provided workarounds, however:

Easiest

expect.getState().currentTestName

This will return the full path to the test, from the outermost describe to the test itself, separated with ' ' (not the best separator), e.g. static methods toString. You can't easily tell which one was the describe name, and which one was the test name.

With some setup, and soon to be obsoleted

The same GitHub issue has this alternative method, which makes the test name accessible directly in the test via jasmine['currentTest'].fullName, no extend needed. Note though that Jasmine will no longer be the default test reported starting in Jest 27.

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(...);
});

Tags:

Jestjs