Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 22 additions & 26 deletions packages/ntpclient/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,44 @@
/* eslint-disable no-magic-numbers */
import type dgram from 'node:dgram';
import {assert, expect, describe, test, beforeEach, vi, afterEach} from 'vitest';
import * as dgram from 'node:dgram';
import {assert, expect, describe, it, beforeEach, vi, afterEach} from 'vitest';
import {NTPClient} from './index.js';

const SECOND_IN_MILLIS = 1000;
const replyTimeout = 10 * SECOND_IN_MILLIS;
const replyTimeout = 5 * SECOND_IN_MILLIS;

describe('NTP', () => {
beforeEach(() => {
vi.mock('dgram', async () => {
const actual = (await vi.importActual('dgram')) as typeof dgram;
const socket = actual.createSocket('udp4');
return {
...actual,
send: () => {
socket.emit(
'message',
Buffer.from([
0x1c, 0x02, 0x03, 0xe8, 0x00, 0x00, 0x02, 0x1a, 0x00, 0x00, 0x05, 0x12, 0xc0, 0x35, 0x67, 0x6c, 0xe9,
0x03, 0x76, 0xff, 0xff, 0x97, 0x0f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe9, 0x03,
0x78, 0x0f, 0xe9, 0xd6, 0x4e, 0x10, 0xe9, 0x03, 0x78, 0x0f, 0xea, 0x03, 0x93, 0xf5,
])
);
},
};
});
vi.mock('node:dgram', async () => ({
...(await vi.importActual<typeof dgram>('node:dgram')),
send: () => {
const socket = dgram.createSocket('udp4');
socket.emit(
'message',
Buffer.from([
0x1c, 0x02, 0x03, 0xe8, 0x00, 0x00, 0x02, 0x1a, 0x00, 0x00, 0x05, 0x12, 0xc0, 0x35, 0x67, 0x6c, 0xe9, 0x03,
0x76, 0xff, 0xff, 0x97, 0x0f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe9, 0x03, 0x78, 0x0f,
0xe9, 0xd6, 0x4e, 0x10, 0xe9, 0x03, 0x78, 0x0f, 0xea, 0x03, 0x93, 0xf5,
])
);
},
}));
});

afterEach(() => {
vi.resetAllMocks();
});

test(
it(
'returns the current time',
async () => {
const ntpClient = new NTPClient({
replyTimeout,
});
const ntpClient = new NTPClient({replyTimeout});
const data = await ntpClient.getNetworkTime();
expect(data).toEqual(expect.any(Date));
},
replyTimeout
);

test(
it(
'works with another NTP server',
async () => {
const ntpClient = new NTPClient({
Expand All @@ -55,7 +51,7 @@ describe('NTP', () => {
replyTimeout
);

test("doesn't work with an invalid NTP server", async () => {
it("doesn't work with an invalid NTP server", async () => {
try {
const ntpClient = new NTPClient({
replyTimeout: SECOND_IN_MILLIS,
Expand Down