Skip to content
Swizec Teller - a geek with a hatswizec.com

The Big Mac index and Jest fetch testing

The Big Mac index is a purchasing power parity index published by The Economist. Jest fetch testing is a tech task so frustrating that it almost made me quit the industry.

Click through for source
Click through for source

Screenshots don't have gifs, here:

I'm writing this so you don't have to read 8234721 different blog posts, stack overflow answers, and GitHub threads with conflicting info on how to get Jest and fetch to play together.

Library where I got it working ๐Ÿ‘‰ bigmac-index-price-calculator.

Context is a project built from scratch without a CLI generator. Maybe that was part of my pain.

How to test fetch requests with Jest

A couple of ground rules:

  1. Our test suite must work offline. You shouldn't be blocked from coding just because you're on an airplane even if coding on an airplane is a terrible idea and you should really get some sleep instead.
  2. Our test suite must be reliable. You don't want to get different results running at different times. No expiring API keys, no changing responses, no network failures.

We're using Jest because it's winning the JavaScript and TypeScript testing market. fetch() because it's the standard way to make API requests.

Our ground rules mean we have to mock requests โ€“ make them return a static object that we set up. Recording and replaying requests would be cool, but as far as I can tell Ruby VCR hasn't made it to the JavaScript world yet.

There's at least 2 fetch mocking libraries I could find: fetch-mock and jest-fetch-mock. Both annoying as shit to set up. fetch-mock was the one I got working in the end.

Jest tests run in node. Node doesn't have fetch. You have to use a library for that too. There's a fetch polyfills and ponyfills and Idontknowwhatelsefills out there. I found at least 3.

isomorphic-fetch is the library I got working in the end.

Let us begin.

Install dependencies

Assuming you've got an empty project initialized with npm init or yarn init, you start by installing everything you'll need

Click through for source
Click through for source

Dev dependencies are those only used in development. We need Jest itself, its type definitions, its TypeScript sister, and fetch-mock.

Using ts-jest gives you TypeScript testing superpowers so you don't have to compile your code first and test second. Test your TypeScript directly. It's nice.

Click through for source
Click through for source

We need isomorphic-fetch both in development and when running live. That way your library doesn't break if used server-side in Gatsby or something.

Configure Jest

Configure Jest in a jest.config.js file. There's a bunch of info out there on where exactly this configuration should live. This is the one that finally worked for me.

Click through for source
Click through for source

We're saying code lives in a /src directory and that typescript files should run with ts-jest.

Mock fetch requests

Jest has built-in support for mocking entire libraries. That was a nice discovery after trying many approaches from many articles and tutorials.

You put files in a __mocks__ directory and they overwrite the library you're calling.

magic giphy

To use fetch-mock instead of isomorphic-fetch in your tests, create a file like this:

Click through for source
Click through for source

This means that every time you import isomorphic-fetch in a test file, it will instead import a sandboxed fetch-mock instance. You can add any other setup you want here. Anything you need for your mocks to work correctly.

BIG WARNING ๐Ÿ‘‰ you have to use the require() syntax. No ES6 imports because this is Node not JavaScript. That tripped me up for hours and rumors say you can get import from to work, but I eventually gave up.

Write a Jest fetch test

We're ready to write a test. Everything should work.

The file I'm testing is called index.ts so my test file is called index.test.ts. Here's an example:

Click through for source
Click through for source

We're in Jest now so we can use modern imports.

Rest mocks before each test so there's no overlap, then mock an API request with a matcher and the response we want. The matcher in my case is a URL string, the exact URL my code is going to call, and the response is a JSON object.

Response code 200 for success and body for the data.

Now when you call fetch(URL) in the code, it won't make an API call, it's just gonna get this response object.

Makes your tests fast, offline, and reliable. โœŒ๏ธ

The Big Mac purchasing parity code we're testing

TDD says to write your test first and your code second, but I actually wrote the code first. Here's the part we're testing above :)

Click through for source
Click through for source

You instantiate ParityPrice with your Ipstack API key (you can get one for free) and call .price() with the price you're trying to parity match.

bigmac-index-price-calculator then calls Ipstack to geolocate your visitor based on IP, looks up their country in the BigMacIndex and returns the adjusted price.

The full version has some continent-based conversions when a country isn't found and a bit of caching so you can call multiple times without making too many requests. It works pretty well.

RIDICULOUS WARNING ๐Ÿ‘‰ notice the const fetch = require() part up top? That's because while modern imports work for Jest files and they definitely work when packaging your library, I couldn't get them to work when testing your library. I tried everything. Nothing worked.

Purchasing power parity on reactfordataviz.com

You can see Big Mac Index purchasing power parity in action on https://reactfordataviz-staging.swizec.now.sh/. Scroll down and you'll see a custom price for your location.

Don't click the button yet though. I haven't wired up the adjusted prices with Gumroad yet.

A lot of people have been asking for this and I think it's a great idea. Value based pricing all the way. If learning React Dataviz gets you a $150,000/year job in USA that's very different value than a $50,000/year job somewhere else.

Cheers,
~Swizec

Did you enjoy this article?

Published on August 22nd, 2019 in Front End, Technical

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works ๐Ÿ‘‡

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet ๐Ÿ“–right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet ๐Ÿ“–

Then get thoughtful letters ๐Ÿ’Œ on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. ๐Ÿ‘Œ"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. โœŒ๏ธ

Have a burning question that you think I can answer?ย I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own? ย Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first ๐Ÿ’ฐ on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax?ย Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you areย โค๏ธ

Created bySwizecwith โค๏ธswizec.com