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
不像上面那样创建新数组吗?
我偶然发现了这个答案,它展示了如何获取当前测试的名称
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)
归档时间: |
|
查看次数: |
5535 次 |
最近记录: |