From f6969da0b8424cf9b4338847ddbc2566c0cdc258 Mon Sep 17 00:00:00 2001 From: sacOO7 Date: Wed, 25 Sep 2024 21:39:27 +0530 Subject: [PATCH] Added unit tests for base64Url encoding and decoding --- src/channel/ably/utils.ts | 8 ++++---- tests/ably/utils.test.ts | 15 ++++++++++++++- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/channel/ably/utils.ts b/src/channel/ably/utils.ts index ee833978..6a13efe9 100644 --- a/src/channel/ably/utils.ts +++ b/src/channel/ably/utils.ts @@ -39,7 +39,7 @@ const isBrowser = typeof window === 'object'; * @param base64 base64 url encoded string * @returns decoded text string */ -export const fromBase64UrlEncoded = (base64: string) => { +export const fromBase64UrlEncoded = (base64: string): string => { const base64Encoded = base64.replace(/-/g, '+').replace(/_/g, '/'); const padding = base64.length % 4 === 0 ? '' : '='.repeat(4 - (base64.length % 4)); const base64WithPadding = base64Encoded + padding; @@ -47,7 +47,7 @@ export const fromBase64UrlEncoded = (base64: string) => { if (isBrowser) { return atob(base64WithPadding); } - return Buffer.from(base64WithPadding, 'base64').toString('binary'); + return Buffer.from(base64WithPadding, 'base64').toString(); }; /** @@ -56,12 +56,12 @@ export const fromBase64UrlEncoded = (base64: string) => { * @param base64 text * @returns base64 url encoded string */ -export const toBase64UrlEncoded = (text: string) => { +export const toBase64UrlEncoded = (text: string): string => { let encoded = '' if (isBrowser) { encoded = btoa(text); } else { - encoded = Buffer.from(text, 'binary').toString('base64'); + encoded = Buffer.from(text).toString('base64'); } return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }; diff --git a/tests/ably/utils.test.ts b/tests/ably/utils.test.ts index 5afb9d5b..2f4859db 100644 --- a/tests/ably/utils.test.ts +++ b/tests/ably/utils.test.ts @@ -1,4 +1,4 @@ -import { parseJwt, toTokenDetails } from '../../src/channel/ably/utils'; +import { fromBase64UrlEncoded, parseJwt, toBase64UrlEncoded, toTokenDetails } from '../../src/channel/ably/utils'; describe('Utils', () => { test('should parse JWT properly', () => { @@ -29,4 +29,17 @@ describe('Utils', () => { expect(tokenDetails.issued).toBe(1654634212000); expect(tokenDetails.token).toBe(token); }); + + test('should encode text into Base64UrlEncoded string', () => { + const normalText = "laravel-echo codebase is of best quality, period!" + const encodedText = toBase64UrlEncoded(normalText); + expect(encodedText).toBe('bGFyYXZlbC1lY2hvIGNvZGViYXNlIGlzIG9mIGJlc3QgcXVhbGl0eSwgcGVyaW9kIQ') + }); + + test('should decode Base64UrlEncoded string into text', () => { + const normalText = "bGFyYXZlbC1lY2hvIGNvZGViYXNlIGlzIG9mIGJlc3QgcXVhbGl0eSwgcGVyaW9kIQ" + const encodedText = fromBase64UrlEncoded(normalText); + expect(encodedText).toBe('laravel-echo codebase is of best quality, period!') + }); + });