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:
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!
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 string
s or number
s.
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.
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.
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