forked from heusalagroup/fi.hg.backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JwtDecodeServiceImpl.test.ts
67 lines (54 loc) · 2.25 KB
/
JwtDecodeServiceImpl.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright (c) 2023. Heusala Group Oy <[email protected]>. All rights reserved.
import { decode as jwsDecode } from 'jws';
import { LogLevel } from "../core/types/LogLevel";
import { JwtDecodeServiceImpl } from "./JwtDecodeServiceImpl";
// Mock the 'jws' module
jest.mock('jws', () => ({
decode: jest.fn(),
}));
beforeAll(() => {
JwtDecodeServiceImpl.setLogLevel(LogLevel.NONE);
});
describe('JwtDecodeServiceImpl', () => {
const mockToken = 'mock.token';
const mockPayload = { aud: 'audience', sub: 'subject', verified: true };
beforeEach(() => {
// Set up the mock jws decode function to return our mock payload
(jwsDecode as jest.Mock).mockReturnValue({
payload: JSON.stringify(mockPayload)
});
});
afterEach(() => {
// Clear the mock after each test
(jwsDecode as jest.Mock).mockClear();
});
test('decodePayload returns decoded payload', () => {
const service = JwtDecodeServiceImpl.create();
const result = service.decodePayload(mockToken);
expect(result).toEqual(mockPayload);
expect(jwsDecode).toHaveBeenCalledWith(mockToken);
});
test('decodePayloadAudience returns audience from payload', () => {
const service = JwtDecodeServiceImpl.create();
const result = service.decodePayloadAudience(mockToken);
expect(result).toBe(mockPayload.aud);
});
test('decodePayloadSubject returns subject from payload', () => {
const service = JwtDecodeServiceImpl.create();
const result = service.decodePayloadSubject(mockToken);
expect(result).toBe(mockPayload.sub);
});
test('decodePayloadVerified returns verified from payload', () => {
const service = JwtDecodeServiceImpl.create();
const result = service.decodePayloadVerified(mockToken);
expect(result).toBe(mockPayload.verified);
});
test('decodePayloadAudience throws error if payload has no aud field', () => {
(jwsDecode as jest.Mock).mockReturnValueOnce({
payload: JSON.stringify({ sub: 'subject', verified: true })
});
const service = JwtDecodeServiceImpl.create();
expect(() => service.decodePayloadAudience(mockToken)).toThrow(TypeError);
});
// More tests...
});