本文介绍了如何使用toString()使Chai显示实际值和期望值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近从should.js切换到chai.js,因为我发现前者在基于浏览器的测试中造成障碍。更改不需要对测试套件进行任何更改,因为支持语法,但是我发现失败的测试输出不再以有用的方式向我显示实际值和预期值:

I recently switched from should.js to chai.js, as I discovered the former was causing snags in browser-based testing. The change didn't require any changes to my test suite, as the syntax is supported, but I see that the output of failing tests no longer shows me the actual and expected values in a useful way:

AssertionError: expected [ Array(9) ] to deeply equal [ Array(9) ]

我可以通过添加以下行来吐出这些值的表示形式:

I can get it to spit out a representation of these values by adding this line:

chai.config.truncateThreshold = 0;

但是,这导致每个值都被详尽输出,包括函数和原型属性。同样非常没用。

However this results in every value being exhaustively output, including functions, and including prototype properties. Also pretty useless.

那么,我是否有某种方式让chai表现得像should.js一样,其中使用其toString()方法显示实际/预期值?

So is there some way I am missing to have chai behave like should.js, where actual/expected values are shown using their toString() method?

推荐答案

使用 .toString获取Chai(v1.10.0)以显示实际值和期望值的一种方法()是在运行时修补其 utils.objDisplay

One way to get Chai (v1.10.0) to show actual and expected values using .toString() is to patch its utils.objDisplay at runtime.

基本要点是:

chai.use(function(_chai,utils) {
  utils.objDisplay = function(obj) { return obj+''; };
});

但是,由于Chai实例化重复项的方式,因此在实践中要稍微复杂一些(即: !== )模块内部引用;在这种情况下,还必须修补 utils.getMessage

However, it's slightly-more complicated to do in practice because of the way Chai instantiates duplicate (ie: !==) module references internally; in this case making it necessary to patch utils.getMessage also.

这里是用来演示整个补丁的小提琴以及 Array 对象的自定义格式的简单示例:

Here is a fiddle to demonstrate the overall patch along with a trivial example of custom formatting for Array objects: https://jsfiddle.net/humbletim/oc1tnqpy/

这篇关于如何使用toString()使Chai显示实际值和期望值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 23:55