How can I get Chai to show actual and expected values using toString()

偶尔善良 提交于 2019-12-10 16:17:20

问题


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.

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?


回答1:


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

The basic gist is:

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

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.

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/



来源:https://stackoverflow.com/questions/26980779/how-can-i-get-chai-to-show-actual-and-expected-values-using-tostring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!