What are Mocha tests?

I am testing an Express Node app with Mocha. I would like to have the following test (comparing two empty arrays):

assert.equal [], []

      

... However, Piss is giving me the following error: AssertionError: [] == []

Which method should you use to compare two empty arrays?

+3


source to share


2 answers


The problem is that an array is a reference type in JavaScript, and hence only that reference is compared. And of course, if you create two different empty arrays, independently of each other, they are two different objects and have two different references.

That is why the test is failing.

You basically have the same problems with objects (no deep equality), although you are often not interested in whether two objects are identical, but whether their content is the same.

This is why I wrote a module to handle this: comparejs . This module, among some other nice things, solves this problem by offering comparison by value and matching by ID for all (!) Types. I guess what you need here.

Since you're specifically asking for a mocha context, I've also written my own assert module called node-assertthat that uses comparejs internally. As a side effect, you end up with a more readable (more fluent) syntax. Instead



assert.equal(foo, bar);

      

You can write

assert.that(foo, is.equalTo(bar));

      

Perhaps this could be for you.

PS: I know self-promotion is unnecessary on Stackoverflow, but in this case, the tools I wrote for myself just solve the original poster question. Therefore, do not post this reply as spam.

+3


source


If you are comparing objects ({} or []) you should use assert.deepEqual()

because if you are doing assert.equal([], [])

you are just comparing references: {} === {}

(or [] === []

) will always be false.



http://nodejs.org/api/assert.html#assert_assert_deepequal_actual_expected_message

+17


source







All Articles