GarethOwen
GarethOwen

Reputation: 6133

Jasmine: How to get name of current test

Is there a way of getting the name of the currently running test?

Some (heavily simplified) code may help explain. I want to avoid the duplication of "test1" / "test2" in the calls to performTest:

describe("My test category", function () {

    function performTest(uniqueName, speed) {
        var result = functionUnderTest(uniqueName, speed);
        expect(result).toBeTruthy();
    }

    it("test1", function () {
        performTest("test1", "fast");
    });

    it("test2", function () {
        performTest("test2", "slow");
    });
});

UPDATE I see the information I need is in:

jasmine.currentEnv_.currentSpec.description

or probably better:

jasmine.getEnv().currentSpec.description

Upvotes: 29

Views: 15527

Answers (3)

Pace
Pace

Reputation: 43827

It's not pretty (introduces a global variable) but you can do it with a custom reporter:

// current-spec-reporter.js

global.currentSpec = null;

class CurrentSpecReporter {

  specStarted(spec) {
    global.currentSpec = spec;
  }

  specDone() {
    global.currentSpec = null;
  }

}

module.exports = CurrentSpecReporter;

Add it to jasmine when you add your other reporters...

const CurrentSpecReporter = require('./current-spec-reporter.js');
// ...
jasmine.getEnv().addReporter(new CurrentSpecReporter());

Then extract the test name during your test/setup as needed...

  it('Should have an accessible description', () => {
    expect(global.currentSpec.description).toBe('Should have an accessible description');
  }

At last, see a sample of currentSpec structure:

{
  "id":"spec15",
  "description":"test1",
  "fullName":"My test category test1",
  "failedExpectations":[],
  "passedExpectations":[],
  "deprecationWarnings":[],
  "pendingReason":"",
  "duration":null,
  "properties":null
}

Upvotes: 11

Ian
Ian

Reputation: 34489

For anyone attempting to do this in Jasmine 2: You can introduce a subtle change to your declarations however that fix it. Instead of just doing:

it("name for it", function() {});

Define the it as a variable:

var spec = it("name for it", function() {
   console.log(spec.description); // prints "name for it"
});

This requires no plug-ins and works with standard Jasmine.

Upvotes: 6

GarethOwen
GarethOwen

Reputation: 6133

jasmine.getEnv().currentSpec.description

Upvotes: 15

Related Questions