javascript - 在NodeJS测试中将值与strictEqual进行比较时,“输入对象相同但引用不相等”?
问题描述
我有一个 Node.js 测试,我在其中断言 Date 类型的两个值应该相等,但是测试意外地以AssertionError [ERR_ASSERTION]: Input objects identical but not reference equal
.
(简化的)测试代码是:
it('should set the date correctly', () => {
// (Code that gets "myActualDate" from the page under test goes here)
const myExpectedDate = new Date('2020-05-06');
assert.strictEqual(myActualDate, myExpectedDate);
});
我应该如何更改此测试代码以使测试通过?
解决方案
测试失败是因为assert.strictEqual,根据文档,使用SameValue 比较,对于 Dates (以及大多数其他类型),如果要比较的两个值不是完全相同的对象引用,则该比较失败。
备选方案 1:使用assert.deepStrictEqual而不是 strictEqual:
assert.deepStrictEqual(myActualDate, myExpectedDate); // Passes if the two values represent the same date
备选方案 2:在比较之前使用 .getTime():
assert.strictEqual(myActualDate.getTime(), myExpectedDate.getTime()); // Passes if the two values represent the same date
推荐阅读
- sql - Postgres:有条件地添加到表中
- c# - 第二个摄像头的 Unity 摄像头平移不起作用
- r - 汇总表中重复测量方差分析的唯一行
- wcf - WCF WebSocket 服务需要安全 TLS/SSL WSS
- regex - Raku 中的否定命名正则表达式或字符类插值
- reactjs - 过滤组件中的 useContext 状态而不更改全局状态
- ruby-on-rails - 如何在标签中使用嵌套属性的翻译,以便我只维护一个翻译?
- reactjs - 在 React 应用程序中,前端是接收原始的 React 代码还是纯 html?
- javascript - 将 React/javascript 字符串对象数组转换为对象数组
- sql - 在同一个表中合并 SQL 查询