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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With