如何解决显示失败测试中预期和收到的全部输出
我有一个比较两个集合的测试,当测试失败时,输出形式为:
- Expected
+ Received
Set {
Position {
"x": 0,- "y": 0,+ "y": 2,},Position {
- "x": 1,- "y": 1,+ "x": 0,+ "y": 0,Position {
- "x": 2,+ "x": 1,"y": 1,}
我发现这很难理解,因为它只是一个文本差异,并且真正的差异被掩盖了(集合相差2个元素,但是输出使得很难分辨出哪个)
这是我通过create-react-app
创建的应用,并且我正在使用npm test
或yarn test
进行测试。我以为命令行arg --expand
可以解决问题,但这似乎并没有改变输出(例如,使用yarn test -- --expand
),我认为问题是通过{{1}传递命令行args }和npm
,但yarn
似乎按预期运行,因此我认为这是可行的。
我对这种现代的前端环境完全陌生,因此,如果我在这里混淆了工具,请原谅我...
这是相关的测试:
--silent
test('calculate neighbors on the edge of the board',() => {
let actual = neighbors(new Position(0,1));
let expected = new Set([
new Position(0,0),new Position(1,1),new Position(2,]);
console.log(actual);
console.log(expected);
expect(actual).toEqual(expected);
})
抑制了这些console.log
,这就是为什么我认为args正在传递的原因。但是也许我误解了--silent
?
--expand
的内容:
package.json
解决方法
Jest在v24中似乎已更改,以提供较少的信息。在Jest 23.6.0中,您获得的输出之前是:
Expected value to equal:
Set {{"x": 0,"y": 0},{"x": 1,"y": 1},{"x": 2,"y": 0}}
Received:
Set {{"x": 0,"y": 2},{"x": 0,"y": 2}}
当Jest版本更改为24.9.0(在package.json
中使用的react-scripts v3.4.1的默认设置)时,不会显示此信息。
测试中的一种解决方法是使用两个.toContain
匹配器而不是.toEqual
:
expect(actual).toContain(expected);
expect(expected).toContain(actual);
(从第一个断言中得出):
Expected value: Set {{"x": 0,"y": 0}}
Received set: Set {{"x": 0,"y": 2}}
请注意,与.toEqual
等效项不同,.toContain
在两个集合之间的顺序不同时会失败,因此您需要将这些集合转换为数组并对它们进行排序以进行正确比较。
您可以捕获期望并在自己方便的时候格式化错误:
test('calculate neighbors on the edge of the board',() => {
let errorFound = false;
let actual = neighbors(new Position(0,1));
let expected = new Set([
new Position(0,0),new Position(1,1),new Position(2,]);
console.log(actual);
console.log(expected);
try {
expect(actual).toEqual(expected);
} catch (e) {
console.error('your personalized error here');
errorFound = true;
}
expect(errorFound).toBe(false); // this is not needed,but helps detecting errors
})
有创意,在这里别管我
test('calculate neighbors on the edge of the board',() => {
let actual = neighbors(new Position(0,1));
let expected = new Set([
new Position(0,]);
console.log(actual);
console.log(expected);
try {
expect(actual).toEqual(expected);
} catch (e) {
console.error('Mismatch between expected and actual neighbors');
for (let i=0;i<expected.length;i++){
try{
expect(expected[i]).toMatch(actual[i])
} catch (inner){
console.error(`At pos ${i} expecting ${expected[i]} but found ${actual[i]}`);
}
}
}
})
这需要数以千计的检查(例如:如果实际位置不足或只是破损,它会打印undefined
吗?但是如果可行的话会很棒,不是吗? ;-)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。