superkytoz
superkytoz

Reputation: 1279

Can't get objects to be equal

I'm getting the following fail message from Mocha:

Uncaught AssertionError: expected Object { name: 'John Doe' } to be Object { name: 'John Doe' }
+ expected - actual

Here is my test code:

describe("A user gets registered", function () {
    it('should create a SINGLE user on /api/register POST', function (done) {
        //calling REGISTER api
        server
                .post('/api/register')
                .send({
                    name: "John Doe",
                    username: "john",
                    password: "open"
                })
                .expect("Content-type", /json/)
                .expect(200)
                .end(function (err, res) {
                    var data = {
                        "name": "John Doe"
                    };
                    res.status.should.equal(200);
                    res.body.should.equal(data);
                    done();
                });
    });
});

And here is my actual code:

router.post('/', function (req, res) {
    var data = {name: 'John Doe'};
    res.status(200).json(data);
});

module.exports = router;

However I shouldn't get a fail message from Mocha, because both object are equally the same. But somehow they aren't so I really don't know what I'm doing wrong.

I have already checked the spacing of both objects so that shouldn't be the case.

Upvotes: 0

Views: 437

Answers (2)

Shilly
Shilly

Reputation: 8589

If both objects have their keys in the same order / have the same structure, you can use JSON.stringify and then compare the strings. This only works if all keys are primitive values though, if there's another object as one of the keys, you'll need something more complex.

Upvotes: 0

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

2 objects cannot be the same even though their data is same, because they are stored in memory as 2 different enitities

var data = {
 name: 'piyush'};

var data1 = {
name: 'piyush'
}

data == data1 //false

Upvotes: 1

Related Questions