在 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/