jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.08k stars 6.44k forks source link

[Feature Request] API to access current test name, filename from within tests #9076

Closed dylang closed 4 years ago

dylang commented 4 years ago

🚀 Feature Proposal

Ability to get the test name (aka title), descriptions (aka ancestorTitles), and filename from within the test at runtime.

Motivation

We want to save a screenshot, log file, or custom snapshots and use the description and name of the test for the filename so it's easy for developers to find and know which test they are from.

Example

description('example', () => {
  description('nested', () => {
    test('generate pdf', async() => {
       const { fullName } = jest.getContext();
       // fullName = 'example nested generate pdf';
       const filename = filenamify(`${fullName}.pdf`);
       await generatePDF(data, filename);
       await visualRegression(filename); 
    });
  });
});
//jest.getContext(): TestContext

interface TestContext {
  descriptions: string[]; // empty array if no describe blocks
  testName: string; // empty string if called in a describe block
  fullName: string; // [ ...descriptions, testName ].join(' ')\
  filename: string; 
}

beforeEach or afterEach: Ideally testName is set to the respective test name and not blank if the context is requested from within beforeEach or afterEach.

__filename: Ideally filename provided because __filename is not ideal when tests call out to other libraries that might need to know the filename of the current test, such as an external library for generating snapshots.

updateSnapshots: We may want to expose if the user is requesting snapshots to be updated. This would make it easier to write custom snapshot tooling.

Pitch

As far as I can tell, this seems impossible to do with external code. I thought about trying with a custom reporter, but it felt like a hack. If there is a documented way to do what I am suggesting I apologize for taking your time with this proposal.

jeysal commented 4 years ago

Duplicate of https://github.com/facebook/jest/issues/7909 (which also seems to have a hack to get this info)

github-actions[bot] commented 3 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.