Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get current test name within the currently running test. #2972

Closed
bahmutov opened this issue Dec 19, 2018 · 17 comments · Fixed by #16652
Closed

Get current test name within the currently running test. #2972

bahmutov opened this issue Dec 19, 2018 · 17 comments · Fixed by #16652
Assignees
Labels
existing workaround pkg/driver This is due to an issue in the packages/driver directory type: enhancement Requested enhancement of existing feature

Comments

@bahmutov
Copy link
Contributor

feature

Sometimes users might need to know the name of the current test (current 'it' block and its parents). It would be nice to add the name to the object Cypress.spec. The name should have parts of each "describe" block from the parent to the test

describe('foo', () => {
  describe('bar', () => {
    it('log spec info', function() {
      console.log(Cypress.spec)
      // {
      //   name: 'filter.spec.js',
      //   relative: 'cypress/integration/filter.spec.js',
      //   absolute: '/Users/janelane/Dev/web-app/cypress/integration/filter.spec.js',
      // . new property "test" with block and test names
      //   test: ['foo', 'bar', 'log spec info']
      // }
    })
  })
})
@bahmutov
Copy link
Contributor Author

currently users can find the test names using helper package https://github.com/bahmutov/its-name but it is less than convenient.

@bahmutov bahmutov added type: enhancement Requested enhancement of existing feature pkg/driver This is due to an issue in the packages/driver directory labels Dec 19, 2018
@cypress-bot cypress-bot bot added the stage: ready for work The issue is reproducible and in scope label Feb 20, 2019
@jennifer-shehane
Copy link
Member

I was looking for this today. I thought maybe just a Cypress.test

@Euregan
Copy link

Euregan commented Jul 12, 2019

It would also be useful to be able to get the whole test names from the beforeEach declared in support files.
Use case I have in mind is generating stubs for each test file, and storing them with a hash of the test they are created for

@Doogiemuc
Copy link

upvote! Would like to have this, too!

@Doogiemuc
Copy link

Doogiemuc commented Aug 23, 2019

[SOLVED]
This worked for me:

beforeEach(function() {
  console.log("=======>>>", Cypress.mocha.getRunner().suite.ctx.currentTest.title)
})

@gabbersepp
Copy link
Contributor

The workaround from @Doogiemuc does not work in all circumstances.
Today after updating from cypress 3.4.1 to 3.6.1 i saw a "cannot read 'title' of undefined" exception a few times.

@gabbersepp
Copy link
Contributor

gabbersepp commented Dec 4, 2019

@jennifer-shehane I am interested in a solution for this. In the beforeEach and afterEach I write logs with the testname in it. Would be nice if we must not rely on this workaround.
I already took a look into the driver package but did not found the place that needs to be modified. Can you give me just a little hint so I do not have to search the whole package for the right place?

@itaditya
Copy link

itaditya commented Dec 9, 2019

This works for me

  it('dashboard to challenge flow is visually correct', function () {
    console.log(this.test.title); // dashboard to challenge flow is visually correct
  });

it only gives me what is inside the it block and that's what I needed.

@cadz7
Copy link

cadz7 commented Dec 11, 2019

I'm planning on accessing the test names in beforeEach for a larger project to conditionally skip them based on whether the test name satisfies certain requirements.
@jennifer-shehane Would you recommend sticking to the workaround suggested by @Doogiemuc? I would like to avoid the situation of depending on a specific version of Cypress incase the workaround breaks for subsequent versions.

@Hecsall
Copy link

Hecsall commented Jan 22, 2020

I encountered a similar issue working on a project where i wanted to add a custom screenshot name at the end of the original cypress-generated filename, so i wrote this little function based on @Doogiemuc solution:

// utils/index.js

function getTestName () {
    let cypressContext = Cypress.mocha.getRunner().suite.ctx.test;
    let testTitles = [];

    function extractTitles (obj) {
        if (obj.hasOwnProperty('parent')) {
            testTitles.push(obj.title);
            let nextObj = obj.parent;
            extractTitles(nextObj);
        }
    }

    extractTitles(cypressContext);
    let orderedTitles = testTitles.reverse();
    let fileName = orderedTitles.join(' -- ');
    return fileName;
}

This function iterates over every parent element saving all their titles in an array, then it reverses it, join it with " -- " and returns the final string.
This way i can use it like this:

import { getTestName } from '../utils';

describe('Describe One', () => {
    describe('Describe Two', () => {
        it('MyTest', () => {
            cy.screenshot(`${getTestName()} -- something`)
            // This will result in 
            // "Describe One -- Describe Two -- MyTest -- something.png"
        })
    })
})

Maybe it's not a beautiful solution, but for now it works, hope it helps

@Karnikel
Copy link

Small addition to the solution of @Doogiemuc and @Hecsall:
If you are using typescipt on Cypress you will get the error
TS2339: Property 'mocha' does not exist on type 'Cypress & EventEmitter'.
To solve this you can write

(Cypress as any).mocha.getRunner().suite.ctx.test

It's a kind of hacky...but it works ;)

@jennifer-shehane jennifer-shehane added the good first issue Good for newcomers label Aug 19, 2020
@jennifer-shehane jennifer-shehane changed the title add test name to Cypress.spec object Get current test name within the currently running test. Aug 19, 2020
@jennifer-shehane jennifer-shehane removed the good first issue Good for newcomers label Aug 19, 2020
@LukasLewandowski
Copy link

Any update on this? How to get the context or describe test value?

@Karnikel
Copy link

@LukasLewandowski: You can use the chrome debugger to observe the object content mentioned above.
There you can get very much informations about your current running test.
E.g. Cypress.mocha.getRunner().suite.ctx.test.title will return the describe string of the current running test.

@hbriese
Copy link

hbriese commented Apr 26, 2021

This is a typescript solution. It'd be nice if they included mocha in their types

const getTestTitle = (test: Mocha.Suite = (Cypress as any).mocha.getRunner().suite.ctx.test): string =>
    test.parent?.title ? `${getTestTitle(test.parent)} -- ${test.title}` : test.title;

Simply call getTestTitle()

@cypress-bot cypress-bot bot added stage: backlog and removed stage: ready for work The issue is reproducible and in scope labels May 6, 2021
@cypress-bot cypress-bot bot added the stage: needs review The PR code is done & tested, needs review label May 24, 2021
@cypress-bot cypress-bot bot added stage: needs review The PR code is done & tested, needs review stage: waiting and removed stage: waiting stage: needs review The PR code is done & tested, needs review labels Jun 22, 2021
@cypress-bot cypress-bot bot added stage: waiting and removed stage: needs review The PR code is done & tested, needs review labels Jul 9, 2021
@pierre-vr
Copy link

pierre-vr commented Jul 22, 2021

This is a typescript solution. It'd be nice if they included mocha in their types

const getTestTitle = (test: Mocha.Suite = (Cypress as any).mocha.getRunner().suite.ctx.test): string =>
    test.parent?.title ? `${getTestTitle(test.parent)} -- ${test.title}` : test.title;

Simply call getTestTitle()

Works now with currentTest instead of test:

beforeEach(() => {
    const getTestTitle = (test: Mocha.Suite = (Cypress as any).mocha.getRunner().suite.ctx.currentTest): string =>
        test.parent?.title ? `${getTestTitle(test.parent)} -- ${test.title}` : test.title
    console.log(getTestTitle())
})

@cypress-bot cypress-bot bot added stage: needs review The PR code is done & tested, needs review and removed stage: waiting labels Jul 28, 2021
@cypress-bot cypress-bot bot added stage: work in progress stage: needs review The PR code is done & tested, needs review and removed stage: needs review The PR code is done & tested, needs review stage: work in progress labels Aug 2, 2021
@cypress-bot
Copy link
Contributor

cypress-bot bot commented Aug 2, 2021

The code for this is done in cypress-io/cypress#16652, but has yet to be released.
We'll update this issue and reference the changelog when it's released.

@cypress-bot
Copy link
Contributor

cypress-bot bot commented Aug 4, 2021

Released in 8.2.0.

This comment thread has been locked. If you are still experiencing this issue after upgrading to
Cypress v8.2.0, please open a new issue.

@cypress-bot cypress-bot bot locked as resolved and limited conversation to collaborators Aug 4, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
existing workaround pkg/driver This is due to an issue in the packages/driver directory type: enhancement Requested enhancement of existing feature
Projects
None yet
Development

Successfully merging a pull request may close this issue.