Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two dates when testing with mocha/chai

I am using "chai": "^4.2.0" and "mocha": "^6.1.4",.

When using assert.equal() to compare two dates I get false even though these two dates seem to be the same:

enter image description here

Here is my example test:

  it('check if dates are correctly added', async () => {
let dataArr = [{'rating_date':'6/6/2019','impact_on_price':'Low'}]   
let priceServ = new PriceService()

// clear all records
priceServ.clearPriceTable()

// add 1 record
const res = await priceServ.createOrUpdatePrice(dataArr)

// get "all" records from the table that have a certain action attribute
const tableValues = await priceServ.getPricesByField('rating_date')
assert.equal(tableValues[0].rating_date, new Date(dataArr[0].rating_date));

});

Any suggestions what I am doing wrong?

I appreciate your replies!

like image 869
Carol.Kar Avatar asked Jul 14 '19 17:07

Carol.Kar


Video Answer


3 Answers

Chai's assert.deepEqual compares Date objects correctly.

const { assert } = require('chai')

const a = new Date(0)
const b = new Date(0)
const c = new Date(1)

assert.deepEqual(a, b) // ok
assert.deepEqual(b, c) // throws

Of course it is necessary that both arguments passed to deepEqual are Date objects, not strings or numbers.

like image 106
diachedelic Avatar answered Oct 23 '22 05:10

diachedelic


Another approach is to import expect rather than assert. You can then use Chai's deep equality check .eql(), ex:

  expect.eql(tableValues[0].rating_date, new Date(dataArr[0].rating_date));

I prefer this approach as failure messages are logged as plain dates making it easier to fix the failing test.

like image 35
Reinhard Höll Avatar answered Oct 23 '22 04:10

Reinhard Höll


As I mentioned in my comment, assert.equal checks for strict equality. Try comparing the timestamps instead:

assert.equal(tableValues[0].rating_date.getTime(), new Date(dataArr[0].rating_date).getTime());

Note that the error messages can be quite ugly when the dates aren't the same. There are libraries for that.

like image 3
Jb31 Avatar answered Oct 23 '22 06:10

Jb31