首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在NodeJS测试中将值与strictEqual进行比较时,是否会出现“输入对象相同但引用不相等”的问题?

在NodeJS测试中将值与strictEqual进行比较时,是否会出现“输入对象相同但引用不相等”的问题?
EN

Stack Overflow用户
提问于 2020-05-06 23:19:24
回答 1查看 2.3K关注 0票数 6

我有一个Node.js测试,我断言Date类型的两个值应该相等,但AssertionError [ERR_ASSERTION]: Input objects identical but not reference equal测试意外失败。

(简化的)测试代码是:

代码语言:javascript
运行
复制
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);
});

我应该如何更改此测试代码以使测试通过?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-06 23:19:24

测试失败的原因是,根据文档,assert.strictEqual使用SameValue comparison,对于日期(以及大多数其他类型),如果要比较的两个值不是完全相同的对象引用,则会失败。

备选方案1:使用assert.deepStrictEqual而不是strictEqual:

代码语言:javascript
运行
复制
assert.deepStrictEqual(myActualDate, myExpectedDate); // Passes if the two values represent the same date

备选方案2:Use .getTime() before comparing

代码语言:javascript
运行
复制
assert.strictEqual(myActualDate.getTime(), myExpectedDate.getTime()); // Passes if the two values represent the same date
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61638863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档