jest-date icon indicating copy to clipboard operation
jest-date copied to clipboard

Can we add an `expect(date).toBeCloseTo(date)` method?

Open 0x326 opened this issue 1 year ago • 1 comments

An assertion like

const expectedDate = ...;
const realDate = getDate();

expect(realDate).toBeSameHourAs(expectedDate); // Usually pass

can fail in this circumstance:

const expectedDate = new Date('2022-12-29 8:59 AM');
const realDate = new Date('2022-12-29 9:00 AM');

expect(realDate).toBeSameHourAs(expectedDate); // Fails

To avoid unstable test assertions, I think an API like the following would be helpful:

expect(new Date('2022-12-29 8:59 AM')).toBeCloseTo(new Date('2022-12-29 9:00 AM')); // Pass

expect(new Date('2022-12-29 8:59 AM')).toBeCloseTo(new Date('2022-12-29 9:00 AM'), {
  precision: 60_000,  // Precision window in miliseconds
}); // Pass

expect(new Date('2022-12-29 8:59 AM')).toBeCloseTo(new Date('2022-12-29 9:00 AM'), {
  precision: 1_000,  // Precision window in miliseconds
}); // Fail

0x326 avatar Dec 29 '22 19:12 0x326