Javascript 开玩笑';s`it.each()`当被称为$predicate时呈现箭头函数源代码的说明 问题定义
Jest允许在Javascript 开玩笑';s`it.each()`当被称为$predicate时呈现箭头函数源代码的说明 问题定义,javascript,typescript,unit-testing,testing,jestjs,Javascript,Typescript,Unit Testing,Testing,Jestjs,Jest允许在中使用测试用例的数据。每个的名称通过$前缀变量 下面的代码产生如下输出: PASS src/array-functions/find-pairwise.spec.ts findPairwise √ should return [1, 2] for [1, 2, 3] and [Function anonymous] (7ms) √ should return [1, 2] for [1, 2, 3] and [Function anonymous] (1ms
中使用测试用例的数据。每个的名称通过$
前缀变量
下面的代码产生如下输出:
PASS src/array-functions/find-pairwise.spec.ts
findPairwise
√ should return [1, 2] for [1, 2, 3] and [Function anonymous] (7ms)
√ should return [1, 2] for [1, 2, 3] and [Function anonymous] (1ms)
√ should return [2, 3] for [1, 2, 3] and [Function anonymous]
√ should return [2, 3] for [1, 2, 3] and [Function anonymous] (1ms)
√ should return [undefined, undefined] for [1, 2, 3] and [Function anonymous]
Test Suites: 1 passed, 1 total
Tests: 5 passed, 5 total
Snapshots: 0 total
Time: 4.061s
Ran all test suites related to changed files.
如您所见,$expected
和$array
变量以人性化的形式呈现(本例中为基本JavaScript数组)。
但是,$predicate
显示的是一个通用文本[Function anonymous]
,而不是它的实际代码。
我知道,如果对JS中的常规函数和箭头函数调用.toString()
,它们都可以公开其源代码。
有没有一种方法可以指示Jest呈现该调用的结果?
我确实尝试了$predicate.toString()
和$(predicate.toString())
,但它们都不起作用
代码
从“/find pairwise”导入{findPairwise};
描述(findPairwise.name,()=>{
每个都是`
数组|谓词|应为
${[1,2,3]}${(l:number,r:number)=>l==1}{[1,2]}
${[1,2,3]}${(l:number,r:number)=>r==2}{[1,2]}
${[1,2,3]}${(l:number,r:number)=>r==3}{[2,3]}
${[1,2,3]}${(l:number,r:number)=>l+r==5}${[2,3]}
${[1,2,3]}${(l:number,r:number)=>l===r}}}${[undefined,undefined]}
`
('should return$expected for$array and$predicate',({array,predicate,expected})=>{
// ^^^^^^^^^^
// ||||||||||
//我想把这个渲染一下
//作为箭头函数的代码。
//例如“(l:编号,r:编号)=>l==1”
//…或者其他类似的东西。
expect(findPairwise(数组,谓词)).toEqual(expected);
});
});
当您为的表
参数使用版本时,jest在幕后使用库从测试数据生成标题(如果测试数据不是基元类型)
不幸的是,出于您的目的,pretty format
库似乎没有使用函数中的toString
方法来格式化它们
作为替代解决方案,您可以将用于表
参数:
it.each([
[ [1, 2], [1, 2, 3], (l, r) => l === 1 ],
[ [1, 2], [1, 2, 3], (l, r) => r === 2 ],
[ [2, 3], [1, 2, 3], (l, r) => r === 3 ],
[ [2, 3], [1, 2, 3], (l, r) => l + r === 5 ],
[ [undefined, undefined], [1, 2, 3], (l, r) => l === r ],
])
('should return %p for %p and %s', (expected, array, predicate) => {
expect(findPairwise(array, predicate)).toEqual(expected);
});
请注意,我已经更改了参数的顺序,以便将期望值放在第一位。这是因为测试数据和标题中占位符之间的映射是基于表的数组版本中it.each
的顺序