I have my function to convert base 64 to url
function convertB64ToUrl(cameraImage: string): string {
const byteString = atob(cameraImage)
const arrayBuffer = new ArrayBuffer(byteString.length)
const uint8Array = new Uint8Array(arrayBuffer)
for (let i = 0; i < byteString.length; i++) {
uint8Array[i] = byteString.charCodeAt(i)
}
const blob = new Blob([arrayBuffer], { type: 'image/jpeg' })
return URL.createObjectURL(blob)
}
Later in my code I used return of this function at src
in <img/>
. It works fine.
My question is how can I properly test it?
I develop only one small test
test('Util function convertB64ToUrl should convert given string to url', () => {
const initialData = convertB64ToUrl(btoa('Hello'))
expect(initialData).toStrictEqual(new Blob(['Hello'], { type: 'image/jpeg' }))
})
I'd use snapshot test here:
import { readFileSync } from 'fs';
import path from 'path';
.....
const imgString = readFileSync(
path.resolve(__dirname, './imageStub.jpg'),
{ encoding: 'base64' }
).toString();
expect(convertB64ToUrl(imgString)).toMatchSnapshot();
Unfortunately, jsdom does not provide implementation for URL.createObjectURL
so you may need to mock it with blob serialization:
global.URL.createObjectURL = blob => someSerializer(blob);
As an option you can use blob-to-base64 package