使用 mocha/chai 进行测试时比较两个日期

Ann*_*lee 6 javascript mocha.js chai

我正在使用"chai": "^4.2.0""mocha": "^6.1.4",

assert.equal()用于比较两个日期时,即使这两个日期似乎相同,我也会出错:

在此处输入图片说明

这是我的示例测试:

  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));
Run Code Online (Sandbox Code Playgroud)

});

任何建议我做错了什么?

我感谢您的回复!

dia*_*lic 11

Chai正确地assert.deepEqual比较了Date对象。

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
Run Code Online (Sandbox Code Playgroud)

当然,传递给的两个参数都必须deepEqualDate对象,而不是strings 或numbers。


小智 7

另一种方法是导入expect而不是assert. 然后您可以使用 Chai 的深度相等检查.eql(),例如:

  expect.eql(tableValues[0].rating_date, new Date(dataArr[0].rating_date));
Run Code Online (Sandbox Code Playgroud)

我更喜欢这种方法,因为失败消息被记录为简单的日期,从而更容易修复失败的测试。