如何在 jest 中获取当前测试索引

Kau*_*era 11 javascript jestjs

如何获取当前测试的test.each索引jest

这就是我现在的做法

test.each([
  [ "Adam", 0 ], // specifying index manually
  [ "Ron", 1 ],
  [ "Roy", 2 ],
])( "Student: %s", ( name, currentTestIndex, done ) => {
  if ( currentTestIndex == 0 ) expect( name ).toEqual( "Adam" )
  if ( currentTestIndex == 2 ) expect( name ).toEqual( "Roy" );
  return done()
} )
Run Code Online (Sandbox Code Playgroud)

如何在不手动指定索引的情况下做到这一点

test.each([
  [ "Adam"], // not specifying the index
  [ "Ron" ],
  [ "Roy" ],
])( "Student: %s", ( name, currentTestIndex, done ) => {

  // how to get current test's index ?
  if ( currentTestIndex == 0 ) expect( name ).toEqual( "Adam" )
  if ( currentTestIndex == 2 ) expect( name ).toEqual( "Roy" );
  return done()
} )
Run Code Online (Sandbox Code Playgroud)

编辑:

现在就这样做,通过创建另一个数组并将map索引添加为第一个元素

test.each([
  [ "Adam" ],
  [ "Ron"  ],
  [ "Roy"  ],
].map( (eachArr,ind) => { //creating new array and adding index as the 1st element
  eachArr.unshift( ind ); 
  return eachArr;
}))( "Student: %s", ( currentTestIndex, name, done ) => {
  if ( currentTestIndex == 0 ) expect( name ).toEqual( "Adam" )
  if ( currentTestIndex == 2 ) expect( name ).toEqual( "Roy" );
  return done()
});
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以从自身获取索引而jest不像上面那样创建新数组吗?

Kau*_*era 1

我偶然发现了这个答案,它展示了如何获取当前测试的名称

console.log(expect.getState().currentTestName);


所以现在我们只需在测试名称中添加这个索引占位符

%# - 测试用例的索引。


function getCurrentTestIndex() {
  const testName = expect.getState().currentTestName;
  const testIndexPos = testName.lastIndexOf(":")+1;
  const currentTestIndex = parseInt( testName.substring( testIndexPos ) )
  return currentTestIndex;
}


test.each(["Adam", "Ron", "Roy"])( "Student: %s :%#", ( name, done ) => {
  const currentTestIndex = getCurrentTestIndex();
  if ( currentTestIndex == 0 ) expect( name ).toEqual( "Adam" )
  if ( currentTestIndex == 2 ) expect( name ).toEqual( "Roy" )

  return done()
})

Run Code Online (Sandbox Code Playgroud)

getCurrentTestIndex()如果您想在测试文件中使用它并且希望避免在任何地方编写 import 语句,您可以将 in 保留为全局

global.getCurrentTestIndex = getCurrentTestIndex;


所以现在我们从 jest 本身获取索引,但我们必须在测试名称中添加索引并提取它。

但如果能以currentTestIndex与我们获取currentTestName.


如果您正在寻找一款内衬

getCurrentTestIndex = _ => parseInt( expect.getState().currentTestName.split(":").at(-1) )
Run Code Online (Sandbox Code Playgroud)