Skip to content

Commit d232d70

Browse files
committed
chore: fix timed log unreliable with Date.now() calls
1 parent 6e369f0 commit d232d70

File tree

2 files changed

+24
-11
lines changed

2 files changed

+24
-11
lines changed

ts/test/session/unit/utils/loggerTimed_test.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import { assert } from 'chai';
2+
import Sinon from 'sinon';
3+
24
import { TimedLog } from '../../../../util/loggerTimed';
35

46
const second = 's';
@@ -20,6 +22,16 @@ function testPairFuzzy({ offset, output }: TimePair) {
2022
}
2123

2224
describe('TimedLog', () => {
25+
const mockNow = 1000000; // arbitrary timestamp
26+
27+
beforeEach(() => {
28+
Sinon.stub(Date, 'now').returns(mockNow);
29+
});
30+
31+
afterEach(() => {
32+
Sinon.restore();
33+
});
34+
2335
describe('formatDistanceToNow', () => {
2436
it('should return exact milliseconds when the time difference is less than 1 second', () => {
2537
(
@@ -82,11 +94,11 @@ describe('TimedLog', () => {
8294
// Millisecond values should be whole numbers but we should still handle non-regular values as its theoretically possible for the time to be a float
8395
(
8496
[
85-
{ offset: 1.11112123213, output: `2${ms}` },
97+
{ offset: 1.11112123213, output: `1${ms}` },
8698
{ offset: 1.567, output: `2${ms}` },
8799
{ offset: 1.867, output: `2${ms}` },
88100
{ offset: 1001.567, output: `1.002${second}` },
89-
{ offset: 2002.1, output: `2.003${second}` },
101+
{ offset: 2002.1, output: `2.002${second}` },
90102
{ offset: 10000.0000001, output: `10${second}` },
91103
] satisfies TimePairs
92104
).forEach(testPair);

ts/util/loggerTimed.ts

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -50,28 +50,29 @@ export class TimedLog {
5050
this.start = Date.now();
5151
}
5252

53+
private static formatMsToSeconds(milliseconds: number): string {
54+
const seconds = milliseconds / 1000;
55+
return seconds.toFixed(3).replace(/\.?0+$/, '');
56+
}
57+
5358
/**
5459
* Format the time elapsed since the start of the timer.
5560
* @param time The time to format.
5661
* @returns The formatted time.
5762
*/
5863
public static formatDistanceToNow(time: number) {
59-
const ms = Date.now() - Math.floor(time);
64+
const ms = Math.round(Date.now() - time);
6065
const s = Math.floor(ms / 1000);
61-
if (s === 0) {
66+
67+
if (ms < 1000) {
6268
return `${ms}${TimedLog.millisecondSuffix}`;
6369
}
6470

65-
if (ms === 0) {
71+
if (ms % 1000 === 0) {
6672
return `${s}${TimedLog.secondSuffix}`;
6773
}
6874

69-
function formatMillisecondsToSeconds(milliseconds: number): string {
70-
const seconds = milliseconds / 1000;
71-
return seconds.toFixed(3).replace(/\.?0+$/, '');
72-
}
73-
74-
return `${formatMillisecondsToSeconds(ms)}${TimedLog.secondSuffix}`;
75+
return `${TimedLog.formatMsToSeconds(ms)}${TimedLog.secondSuffix}`;
7576
}
7677

7778
/**

0 commit comments

Comments
 (0)