0

I have a vitest test in the following form:

beforeEach(async () => {
  // ???
})

describe('Subject Under Test', () => {
    test('should behave as expected', async () => {
    });
});

How do I go about getting 'Subject Under Test' and 'should behave as expected' as strings within beforeEach?

2 Answers 2

1
beforeEach((context) => {
    console.log(context.task.name);
    console.log(context.task.parent.name);
});

or

beforeEach(({task}) => {
    console.log(task.name);
    console.log(task.parent.name);
});

Either should work. See Vitest's context documentation for more information. You can find more documentation about parent and other options like fullName at Vitest's TestCase page. If you need to go up more than one level, parent can do that.

Note that the documentation is talking about doing it in a test, but at the bottom, it talks about accessing context in a beforeEach. It's a bit odd in that you'd usually put test-specific behavior in the test block, not the beforeEach. However, the context is available for modification in the beforeEach and is supposed to be available for access as well.

Sign up to request clarification or add additional context in comments.

Comments

0

The following works:

beforeEach(async ({task}) => {
    console.log(`*************** Before test ${task.suite.name} ***************`);
    console.log(`*************** Before test ${task.name} ***************`);
})

although task.suite.name reports only the inner-most describe name if they're nested

task.suite.suite.name will report one level up a describe nesting

A function can be written to return an array of nested describe names

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.