Get the current test/spec name in Jest

前端 未结 3 614
耶瑟儿~
耶瑟儿~ 2021-01-18 08:19

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 nam

3条回答
  •  旧时难觅i
    2021-01-18 08:59

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

提交回复
热议问题