relief.melone
relief.melone

Reputation: 3322

Comparing Objects with Dates from MongoDb in Mocha

I'm currently having a problem with a test in mocha. I want to test a getById method that is returning an object from a mongodb database. Everything works fine, except for the comparison of the date. This is what i do.

describe('Service.Step.getById', function(){

before(done => {
    mongoose.connect(getConnectionString());
    mongoose.connection.on('error', () => {
        console.error("Connecting to database failed");
    });
    mongoose.connection.once('open', () => {
        console.log('Connected to Database');
        done();
    });
});

it('should return a step', async function(){
    assert.equal((await StepService.getById("someId")).toObject(), {
        Title : "SomeTitle",
        _id: mongodb.ObjectID("someId"),
        SchemaVersion : "0.0.1",
        Description: "SomeDescription",
        Video: "Video.mp4",
        Image : null,
        __v : 0,
        Created : "2018-09-05T15:24:11.779Z",
        Updated :  "2018-09-05T15:24:11.779Z"
    });
});

Now the problem is, that obviously mongoose returns a Date Object and not just a string. (this is what the test shows)

  • "Updated": [Date: 2018-09-05T15:24:11.779Z]
  • "Updated": "2018-09-05T15:24:11.779Z"

however if i replace the Created (or Updated) in the assert to

Created : new Date("2018-09-05T15:24:11.779Z")

my test fails completely. Do you know how i could fix this?

Upvotes: 2

Views: 986

Answers (2)

Igor Litvinovich
Igor Litvinovich

Reputation: 2502

equal asserts non-strict equality (==) of actual and expected. e.g.

{a:1} == {a:1} //false

deepEqual asserts that actual is deeply equal to expected

assert.deepEqual({ tea: 'green' }, { tea: 'green' }); //true

Upvotes: 2

relief.melone
relief.melone

Reputation: 3322

Ok. The answer was acually pretty simple. It seems that a Date will make the object nested and

assert.equal

will not work for this anymore. Instead use

assert.deepEqual

and it will work as expected. The correct code would be

before(done => {
    mongoose.connect(getConnectionString());
    mongoose.connection.on('error', () => {
        console.error("Connecting to database failed");
    });
    mongoose.connection.once('open', () => {
        console.log('Connected to Database');
        done();
    });
});

it('should return a step', async function(){
    assert.deepEqual((await StepService.getById("someId")).toObject(), {
        Title : "SomeTitle",
        _id: mongodb.ObjectID("someId"),
        SchemaVersion : "0.0.1",
        Description: "SomeDescription",
        Video: "Video.mp4",
        Image : null,
        __v : 0,
        Created : new Date("2018-09-05T15:24:11.779Z"),
        Updated : new Date("2018-09-05T15:24:11.779Z")
    });
});

Upvotes: 0

Related Questions