Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What are Mocha equal tests?

What are Mocha equal tests?

Problem

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?

Problem courtesy of: AdamNYC

Solution

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.

Solution courtesy of: Golo Roden

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

What are Mocha equal tests?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×