Testing with Images in Javascript

· 444 words · 3 minute read

How to import an image in Javascript to be used in Jest Tests

This article was originally posted on Medium.


How I feel working with Javascript sometimes


The Story 🔗

I was assigned with writing tests using images for an endpoint I created at work. The tests and endpoints were written in Javascript using Jest and Node.js, respectively. I figured it wouldn’t be too difficult — opening a file or image is something I’m familiar with in Java and Python, but the only experience I had doing this in Javascript was when there was a frontend available to pass in the image information. I had some idea of how to do this, so I was determined to figure it out on my own instead of turning to others to get the direct answer. But, as we all know — knowing how to do something in one language doesn’t mean you understand how to do it in another language. I ended up struggling to figure out exactly how to open the image and be able to pass it as a variable and convert it to base64 without acquiring it from a frontend.(Spoiler alert: I ended up asking people)

The Process 🔗

In order to clear up exactly how to do this, I turned to the place (almost) everyone turns to when they have a question: Google.

I executed a total of 31 unique queries. I also ended up asking two separate groups of people for how to do this:

include image in javascript test body
image as variable javascript
image as variable javascript testing
image as variable javascript backend
javascript test with image
javascript test with image backend
javascript access image
javascript react imge
handling image as variable javascript
image representation in code
image in code
javascript json binary object
transfer binary data json javascript
javascript send image to server
javasript image
javascript image from file
javascript image from local file
access local image javascript
use image for testing javascript
read image javascript frm file
mock image javascript
ask friends
filereader
javascript filereader
javascript filereader image
javascript filereader example
javascript filereader image testing site:stackoverflow.com
javascript image blob
javascript create blob from image local
read image from fille javascript filereader
read local file filereader
jest test with image
json send image
ask coworker
base 64 to buffer
readFileSync

The Final Solution 🔗

It was a total of two lines of code. Use the method readFileSync and then convert to a base64 string. In code:

var imgFile = readFileSync(pathToImage)
var fileStr = imgFile.toString(“base64”)

For those curious, readFileSync returns a type of type { ext: 'jpg', mime: 'image/jpeg'} which can then be converted to base64.

Simple.

I hope this article helps you streamline your image working process, and save you 31 unique Google queries.