4

I would like to know the proper way to compare objects in a unit test. For the purpose of this example, I am using assert and mocha to test a simple library mylib with a method method that returns an object.

var assert = require("assert");
var mylib = require("../src/mylib");

describe("method", function() {
  it("does something clever and returns an object", function() {
    assert.equal(
      JSON.stringify({/* expected object */}), 
      JSON.stringify(mylib.method(["items", "in", "the", "list"])));
  });
});

The above works, but I don't know if using JSON.stringify is a recommended practice. Am I doing this right?

1 Answer 1

5

You should not use JSON.stringify, the problem with this approach is according to MDN JSON.stringify()

Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.

As of that you might compare {"a":2, "b":3} with {"b":3, "a":2}.

Instead of that you should use e.g. assert.deepEqual(to be honest I never used assert but as of the naming it should be the correct function)

Sign up to request clarification or add additional context in comments.

4 Comments

assert.deepEqual is spot on. Oh to think of the gymnastics I went through before I learned that it was there.
Thank you. Node's documentation was a bit lacking. Any particular reasons for not using assert?
@JorgeBucaran no, I just like chai better, because the style is a bit more verbose e.g. expect(foo).to.deep.equal({ bar: 'baz' }); or expect(beverages).to.have.property('tea').with.length(3);. And in my opinion fits great into the way mocha is styled.
expect(foo).to.deep.equal({ bar: 'baz' }); works for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.