Skip to content

Commit

Permalink
Added unit tests for base64Url encoding and decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
sacOO7 committed Sep 25, 2024
1 parent 4e78bf6 commit f6969da
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
8 changes: 4 additions & 4 deletions src/channel/ably/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ 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;

if (isBrowser) {
return atob(base64WithPadding);
}
return Buffer.from(base64WithPadding, 'base64').toString('binary');
return Buffer.from(base64WithPadding, 'base64').toString();
};

/**
Expand All @@ -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(/=+$/, '');
};
Expand Down
15 changes: 14 additions & 1 deletion tests/ably/utils.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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!')
});

});

0 comments on commit f6969da

Please sign in to comment.