问题
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