Skip to content

Commit 3b017ef

Browse files
authored
Add unit tests for decodeJWT function to validate JWT decoding (#55)
Signed-off-by: Joye Lin <y12studio@gmail.com>
1 parent 03cfb1e commit 3b017ef

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/test/jwt.spec.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,32 @@ describe('JWT', () => {
1414
expect(jwt.payload).toEqual({ foo: 'bar' });
1515
});
1616

17+
test('returns decoded JWT when correct JWT string is provided', () => {
18+
// Two objects are created separately, the first: { alg: 'HS256', typ: 'JWT' } represents a JWT Header and the second: { sub: '1234567890', name: 'John Doe' } represents a JWT Payload.
19+
// These objects are turned into strings with JSON.stringify. The resulting strings are encoded with base64 encoding using Buffer.from(string).toString('base64').
20+
// These base64 encoded strings are concatenated with a period (.) between them, following the structure of a JWT, which is composed of three Base64-URL strings separated by dots (header.payload.signature).
21+
// A 'signature' string is added at the end to represent a JWT signature.
22+
// So, the jwt variable ends up being a string with the format of a base64Url encoded Header, a period, a base64Url encoded Payload, another period, and a 'signature' string.
23+
// It's important to note that the 'signature' here is just a placeholder string and not an actual cryptographic signature generated from the header and payload data.
24+
const jwt = `${Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64')}.${Buffer.from(JSON.stringify({ sub: '1234567890', name: 'John Doe' })).toString('base64')}.signature`;
25+
const result = Jwt.decodeJWT(jwt);
26+
expect(result).toEqual({
27+
header: { alg: 'HS256', typ: 'JWT' },
28+
payload: { sub: '1234567890', name: 'John Doe' },
29+
signature: 'signature',
30+
});
31+
});
32+
33+
test('throws an error when JWT string is not correctly formed', () => {
34+
const jwt = 'abc.def';
35+
expect(() => Jwt.decodeJWT(jwt)).toThrow('Invalid JWT as input');
36+
});
37+
38+
test('throws an error when JWT parts are missing', () => {
39+
const jwt = `${Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64')}`;
40+
expect(() => Jwt.decodeJWT(jwt)).toThrow('Invalid JWT as input');
41+
});
42+
1743
test('set', async () => {
1844
const jwt = new Jwt();
1945
jwt.setHeader({ alg: 'EdDSA' });

0 commit comments

Comments
 (0)