From 26cdab990789835d59e1347229987a623036779c Mon Sep 17 00:00:00 2001 From: Brendan Chen Date: Mon, 24 Mar 2025 09:48:35 -0700 Subject: [PATCH] copy over test for APNs token reload --- .../AppleNotificationSenderTests.test.ts | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 test/notifications/senders/AppleNotificationSenderTests.test.ts diff --git a/test/notifications/senders/AppleNotificationSenderTests.test.ts b/test/notifications/senders/AppleNotificationSenderTests.test.ts new file mode 100644 index 0000000..c4fddb5 --- /dev/null +++ b/test/notifications/senders/AppleNotificationSenderTests.test.ts @@ -0,0 +1,66 @@ +import { beforeEach, describe, expect, it, jest } from "@jest/globals"; +import http2 from "http2"; +import { EventEmitter } from "node:events"; +import { AppleNotificationSender } from "../../../src/notifications/senders/AppleNotificationSender"; + +jest.mock("http2"); + +const sampleKeyBase64 = "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JR1RBZ0VBTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEJIa3dkd0lCQVFRZ3NybVNBWklhZ09mQ1A4c0IKV2kyQ0JYRzFPbzd2MWJpc3BJWkN3SXI0UkRlZ0NnWUlLb1pJemowREFRZWhSQU5DQUFUWkh4VjJ3UUpMTUJxKwp5YSt5ZkdpM2cyWlV2NmhyZmUrajA4eXRla1BIalhTMHF6Sm9WRUx6S0hhNkVMOVlBb1pEWEJ0QjZoK2ZHaFhlClNPY09OYmFmCi0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K"; + +function mockHttp2Connect(status: number) { + class MockClient extends EventEmitter { + request = jest.fn((headers: any) => { + const mockRequest: any = new EventEmitter(); + mockRequest.setEncoding = jest.fn(); + mockRequest.write = jest.fn(); + mockRequest.end = jest.fn(() => { + setTimeout(() => { + mockRequest.emit('response', { ':status': status }); + }, 10); + }); + return mockRequest; + }); + + close() {}; + } + + (http2.connect as jest.Mock) = jest.fn(() => new MockClient()); +} + +describe("AppleNotificationSender", () => { + let notificationSender: AppleNotificationSender; + + beforeEach(() => { + notificationSender = new AppleNotificationSender(); + + // Ensure that tests don't hit the server + process.env = { + ...process.env, + APNS_KEY_ID: "1", + APNS_TEAM_ID: "1", + APNS_BUNDLE_ID: "dev.bchen.ProjectInter", + APNS_PRIVATE_KEY: sampleKeyBase64, + }; + }); + + beforeEach(() => { + mockHttp2Connect(200); + }); + + describe("reloadAPNsTokenIfTimePassed", () => { + it("reloads the token if token hasn't been generated yet", async () => { + notificationSender.reloadAPNsTokenIfTimePassed(); + expect(notificationSender.lastRefreshedTimeMs).toBeDefined(); + }); + + it("doesn't reload the token if last refreshed time is recent", async () => { + notificationSender.reloadAPNsTokenIfTimePassed(); + const lastRefreshedTimeMs = notificationSender.lastRefreshedTimeMs; + + notificationSender.reloadAPNsTokenIfTimePassed(); + // Expect no change to have occurred + expect(lastRefreshedTimeMs).toEqual(notificationSender.lastRefreshedTimeMs); + }); + }); + +});