Jasmine: How to get name of current test

你离开我真会死。 提交于 2019-12-01 15:47:38
jasmine.getEnv().currentSpec.description

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.

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');
  }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!