Hey there! Today, I've been working on unit testing a CloudFlare's wrangler
worker. It is a new topic for me, and I decided to dive into it by unit testing it. Hope you can get something useful for yourself.
Prehistory
My Photohub is Seneca's starter project, where students build it from scratch, lead by David Humphrey. It is designed to create repos in user's GitHub accounts with their own website, and to do so, they decided to use cloud workers on CloudFlare. And such, unit tests were needed for the worker.
Working and some challenges along the way
Firstly, I needed to add all proper dependencies for testing. Since the worker was written using Node.js, I decided to go with Jest. There weren't things to configure, so I just went ahead with regular configuration.
For unit testing, I used guidance at worker docs. First strange thing I encountered was that file path for unstable_dev
had to be written from root directory perspective, and not the test file location. Embarrassingly, I spent around 10 minutes to understand that, having to reverse-engineer it.
I set the test to expect the login form on GET fetch, but there was another issue. Apparently, jest does not have regular JS Response objects built-in. For that, I installed another dev-dependency called isomorphic-fetch
that provided an alternative and imported it into the test file using require('isomorphic-fetch');
. After that, I was done with GET fetch.
POST fetch, on the other hand, was not as simple as returning a simple HTML form. It was connecting to GitHub on users behalf and creating a repo. I didn't feel like I could fit all that into a unit test, so I asked other contributors if they thought it could be possible. Sometimes, we just need other's opinion on a certain matter.
After all changes have been committed, I opened a pull request and reached out for feedback.
Top comments (0)