问题
I am testing an Express Node app with Mocha. I would like to have the following test (comparing two empty arrays):
assert.equal [], []
to pass. However, Mocha gives me the following error:
AssertionError: [] == []
Which method should I use in order for comparison of two empty arrays to pass?
回答1:
The problem is that an array is a reference type in JavaScript, and hence only the reference is compared. And, of course, if you create two different empty arrays independent of each other, they are two different objects and have two different references.
That's why the test fails.
You basically have the same issues with objects (no deep-equal is done), although you often are not interested in whether two objects are identical, but whether their contents are the same.
That's why I wrote a module to handle this: comparejs. This module - besides some other nice things - solves this issue by offering comparison by value and comparison by identity, for all (!) types. I guess that's what you need here.
As you are especially asking for the context of mocha, I have also written my own assert-module, called node-assertthat, which internally makes use of comparejs. As a side effect, you get a more readable (as more fluent) syntax. Instead of
assert.equal(foo, bar);
you can write
assert.that(foo, is.equalTo(bar));
Perhaps this may be the way for you to go.
PS: I know that self-advertisement is not wanted on Stackoverflow, but in this case the tools I've written for myself simply solve the original poster's question. Hence please do not mark this answer as spam.
回答2:
If you're comparing objects ({} or []) you have to use assert.deepEqual()
because if you do assert.equal([], [])
you're just comparing the references: {} === {}
(or [] === []
) will be always false.
http://nodejs.org/api/assert.html#assert_assert_deepequal_actual_expected_message
来源:https://stackoverflow.com/questions/14543979/what-are-mocha-equal-tests