Skip to content

Commit 4857657

Browse files
authored
Merge pull request #1572 from session-foundation/fix-timed-log-unit-tests
chore: fix timed log unreliable with Date.now() calls
2 parents 7a6e3e9 + 0b11036 commit 4857657

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
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: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ export class TimedLog {
5050
this.start = Date.now();
5151
}
5252

53-
private static formatMillisecondsToSeconds(milliseconds: number): string {
53+
private static formatMsToSeconds(milliseconds: number): string {
5454
const seconds = milliseconds / 1000;
5555
return seconds.toFixed(3).replace(/\.?0+$/, '');
5656
}
@@ -61,17 +61,18 @@ export class TimedLog {
6161
* @returns The formatted time.
6262
*/
6363
public static formatDistanceToNow(time: number) {
64-
const ms = Date.now() - Math.floor(time);
64+
const ms = Math.round(Date.now() - time);
6565
const s = Math.floor(ms / 1000);
66-
if (s === 0) {
66+
67+
if (ms < 1000) {
6768
return `${ms}${TimedLog.millisecondSuffix}`;
6869
}
6970

70-
if (ms === 0) {
71+
if (ms % 1000 === 0) {
7172
return `${s}${TimedLog.secondSuffix}`;
7273
}
7374

74-
return `${this.formatMillisecondsToSeconds(ms)}${TimedLog.secondSuffix}`;
75+
return `${TimedLog.formatMsToSeconds(ms)}${TimedLog.secondSuffix}`;
7576
}
7677

7778
/**

0 commit comments

Comments
 (0)