javascript - 将测试中的日期与 Jasmine 进行比较时出错

标签 javascript angular unit-testing jasmine

在 Angular 测试中比较“日期”时出现错误。测试显示错误,但在日志本身中它是正确的。

我的测试:

it('myTest', () => {
      const today = new Date();
      component.minDate = null;
      component.maxDate = null;

      spyOnProperty(component, 'isRange').and.returnValue(false);
      component['setActivateDate'](null);

      spyOn(component, <any>'verifyActivateDate').and.callThrough();

      expect(component.activateDate).toEqual(today);
    });

记录“错误”

Error: Expected Date(Wed Nov 17 2021 20:28:54 GMT+0000 (Coordinated Universal Time)) to equal Date(Wed Nov 17 2021 20:28:54 GMT+0000 (Coordinated Universal Time)).
        at <Jasmine>

最佳答案

您要比较的日期看起来相等,因为字符串表示形式仅显示秒的值。在此之前,您的日期是相等的,但在毫秒范围内有所不同,该范围不会显示(但是相等检查的一部分)。

您可以使用库(例如 dayjs)进行比较,也可以自己实现“几乎相等”检查。

// Pass the dates you want to compare and an "accuracy" value.
// The accuracy removes that number of digits from the timestamp,  of
// so the default value of "3" means "remove the last 3 digits", which
// effectively means you are only comparing up until seconds
const expectDatesToNearlyEqual = (d1: Date, d2: Date, accuracy: number = 3) => {
   // Timestamp of first date, removing "accuracy" amount of digits from the end
   const d1Time = Math.floor(+d1 / (accuracy * 10));  
   // Timestamp of second date, removing "accuracy" amount of digits from the end
   const d2Time = Math.floor(+d2 / (accuracy * 10));

   // Expect the timestamps to equal, if they are not, print a nice message (optional).
   expect(d1Time).withContext(`${d1} and ${d2} are not equal`).toEqual(d2Time);
}

关于javascript - 将测试中的日期与 Jasmine 进行比较时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70011245/

相关文章:

javascript - Appium iOS 获取上下文不工作

javascript - JS函数不访问所有数组图片

Django 属性错误 : object has no attribute 'assertContains'

javascript - 如何停止/取消以 "Run JS Tests"开始且耗时过长的 Chutzpah 测试运行?

javascript - 在 AngularJS 中,为什么当指令属性的范围变量是驼峰式时需要用连字符分隔?

Angular2 - 将值传递给使用 ComponentFactory 创建的动态组件

javascript - 如何在 Angular Reactive Form 的嵌套数组字段中构建字段数组?

javascript - 将路线另存为图像 bing map

java - intellij IDEA 如何给 Java 项目添加单元测试?

java - JUnit 测试类失败测试