|
| 1 | +/** |
| 2 | + * @jest-environment node |
| 3 | + */ |
| 4 | + |
| 5 | +import { generateClientAssertion } from "@src/utils/auth/generate-refresh-client-assertion"; |
| 6 | +import pemToCryptoKey from "@src/utils/auth/pem-to-crypto-key"; |
| 7 | +import { AppConfig } from "@src/utils/config"; |
| 8 | + |
| 9 | +jest.mock("@src/utils/auth/pem-to-crypto-key"); |
| 10 | + |
| 11 | +const mockConfig = { |
| 12 | + NHS_LOGIN_PRIVATE_KEY: "mock-private-key", |
| 13 | + NHS_LOGIN_CLIENT_ID: "mock-client-id", |
| 14 | + NHS_LOGIN_URL: "https://mock.nhs.login", |
| 15 | +} as AppConfig; |
| 16 | + |
| 17 | +describe("generateClientAssertion", () => { |
| 18 | + let randomUUIDSpy: jest.SpyInstance; |
| 19 | + let subtleSignSpy: jest.SpyInstance; |
| 20 | + |
| 21 | + beforeAll(() => { |
| 22 | + randomUUIDSpy = jest |
| 23 | + .spyOn(global.crypto, "randomUUID") |
| 24 | + .mockReturnValue("mock-jti"); |
| 25 | + subtleSignSpy = jest |
| 26 | + .spyOn(global.crypto.subtle, "sign") |
| 27 | + .mockResolvedValue(new Uint8Array([1, 2, 3, 4]).buffer); |
| 28 | + }); |
| 29 | + |
| 30 | + beforeEach(() => { |
| 31 | + // Reset mocks before each test |
| 32 | + (pemToCryptoKey as jest.Mock).mockReset(); |
| 33 | + randomUUIDSpy.mockClear(); |
| 34 | + subtleSignSpy.mockClear(); |
| 35 | + }); |
| 36 | + |
| 37 | + afterAll(() => { |
| 38 | + // Restore original implementations after all tests in this describe block |
| 39 | + randomUUIDSpy.mockRestore(); |
| 40 | + subtleSignSpy.mockRestore(); |
| 41 | + }); |
| 42 | + |
| 43 | + it("should generate a client assertion JWT string", async () => { |
| 44 | + (pemToCryptoKey as jest.Mock).mockResolvedValue({} as CryptoKey); |
| 45 | + |
| 46 | + const token = await generateClientAssertion(mockConfig); |
| 47 | + |
| 48 | + expect(typeof token).toBe("string"); |
| 49 | + const parts = token.split("."); |
| 50 | + expect(parts.length).toBe(3); |
| 51 | + |
| 52 | + expect(pemToCryptoKey).toHaveBeenCalledWith( |
| 53 | + mockConfig.NHS_LOGIN_PRIVATE_KEY, |
| 54 | + ); |
| 55 | + |
| 56 | + expect(global.crypto.randomUUID).toHaveBeenCalled(); |
| 57 | + |
| 58 | + expect(global.crypto.subtle.sign).toHaveBeenCalledWith( |
| 59 | + { name: "RSASSA-PKCS1-v1_5", hash: "SHA-512" }, |
| 60 | + expect.anything(), // privateKey |
| 61 | + expect.any(Uint8Array), |
| 62 | + ); |
| 63 | + }); |
| 64 | + |
| 65 | + it("should throw if pemToCryptoKey rejects", async () => { |
| 66 | + (pemToCryptoKey as jest.Mock).mockRejectedValue(new Error("Invalid key")); |
| 67 | + |
| 68 | + await expect(generateClientAssertion(mockConfig)).rejects.toThrow( |
| 69 | + "Invalid key", |
| 70 | + ); |
| 71 | + |
| 72 | + expect(pemToCryptoKey).toHaveBeenCalledWith( |
| 73 | + mockConfig.NHS_LOGIN_PRIVATE_KEY, |
| 74 | + ); |
| 75 | + expect(global.crypto.randomUUID).not.toHaveBeenCalled(); |
| 76 | + expect(global.crypto.subtle.sign).not.toHaveBeenCalled(); |
| 77 | + }); |
| 78 | +}); |
0 commit comments