Skip to content

Commit 8653948

Browse files
authored
test for base64Utils.js (#4334)
* Creating base64Utils.test.js for Unit testing of base64Utils * refactoring base64Utils for proper implementation of test
1 parent efa6675 commit 8653948

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

js/__tests__/base64Utils.test.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
const base64Utils = require('../base64Utils');
2+
global.TextEncoder = require('util').TextEncoder;
3+
global.TextDecoder = require('util').TextDecoder;
4+
5+
describe('base64Utils', () => {
6+
test('base64Encode should correctly encode a string to Base64', () => {
7+
expect(base64Utils.base64Encode('hello')).toBe('aGVsbG8=');
8+
expect(base64Utils.base64Encode('Base64 Encoding!')).toBe('QmFzZTY0IEVuY29kaW5nIQ==');
9+
expect(base64Utils.base64Encode('123456')).toBe('MTIzNDU2');
10+
});
11+
12+
test('base64Decode should correctly decode a Base64 string', () => {
13+
expect(base64Utils.base64Decode('aGVsbG8=')).toBe('hello');
14+
expect(base64Utils.base64Decode('QmFzZTY0IEVuY29kaW5nIQ==')).toBe('Base64 Encoding!');
15+
expect(base64Utils.base64Decode('MTIzNDU2')).toBe('123456');
16+
});
17+
18+
test('base64Encode and base64Decode should be reversible', () => {
19+
const originalText = 'Reversible Test!';
20+
const encoded = base64Utils.base64Encode(originalText);
21+
const decoded = base64Utils.base64Decode(encoded);
22+
expect(decoded).toBe(originalText);
23+
});
24+
25+
test('base64Encode should handle empty strings', () => {
26+
expect(base64Utils.base64Encode('')).toBe('');
27+
});
28+
29+
test('base64Decode should handle empty strings', () => {
30+
expect(base64Utils.base64Decode('')).toBe('');
31+
});
32+
});

js/base64Utils.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ function base64Encode(str) {
1212
let encoder = new TextEncoder();
1313
let uint8Array = encoder.encode(str);
1414
let binaryString = String.fromCharCode(...uint8Array);
15-
return (binaryString);
15+
return btoa(binaryString); // Proper Base64 encoding
1616
}
1717

1818
/**
@@ -27,5 +27,6 @@ function base64Decode(str) {
2727
return decoder.decode(uint8Array);
2828
}
2929

30-
export default { base64Encode, base64Decode };
31-
//module.exports = { base64Encode, base64Decode };
30+
if (typeof module !== 'undefined' && module.exports) {
31+
module.exports = { base64Encode, base64Decode };
32+
}

0 commit comments

Comments
 (0)