如何在Jest的it.each测试描述中使用测试数据变量
Jest测试描述中带引号显示参数的方法
要让测试名称里的property参数带单引号显示,只需在测试描述字符串中给$property包裹单引号即可,有两种实现方式:
方法一:直接在模板字符串中添加单引号
修改测试描述的字符串,用双引号包裹整个描述,内部给$property加上单引号:
it.each([ { property: 'nice test', expectedResult:'nice test' }, { property: 'failed test', expectedResult: 'nice failed test' }, ])("Should property and expectedResult be the same for property: '$property'", ({ property, expectedResult }) => { expect(property).toBe(expectedResult); });
运行时就会输出你期望的测试名称:
Running > "Should property and expectedResult be the same for property: 'nice test'"
Running > "Should property and expectedResult be the same for property: 'failed test'"
方法二:使用函数形式生成测试描述
如果需要对参数做更复杂的格式化处理,可以用函数返回测试描述:
it.each([ { property: 'nice test', expectedResult:'nice test' }, { property: 'failed test', expectedResult: 'nice failed test' }, ])( ({ property }) => `Should property and expectedResult be the same for property: '${property}'`, ({ property, expectedResult }) => { expect(property).toBe(expectedResult); } );
这种方式灵活性更高,适合需要拼接、转换参数的场景。
内容的提问来源于stack exchange,提问作者Ricardo Rocha
相关产品推荐
相关产品推荐

