Testing @loadable/components with Jest

Jake Ginnivan
Jan 7 · 1 min read

We have recently switched from react-loadable to @loadable/components for a number of reasons but had a hard time getting our tests to continue passing.

In react-loadable we would preload the components at the top of the test file so they would render synchronously, this behavior is quite hard to achieve in @loadable/components unless you use Webpack to compile your tests.

We use TypeScript in our project, but the below can be adapted to non-typescript projects as well.

Our solution

We wrote jest mocks for the loadable components modules rather than trying to get the library to play nice.

The mock module eagerly calls the load function to kick off resolving the module, this would mean we had a race condition. So I also provide an implementation of load which returns the promise for the loading module.

__mocks__/@loadable/component.tsx
__mocks__/@loadable/server.ts

Finally our ts-jest config to ensure the dynamic imports work

jest.config.js

I hope this saves you some time!

Pixel and Ink

Jake Ginnivan

Written by

Tech lead for @sevenwestmedia WA | Speaker | Mentor | OSS enthusiast | Full Stack TypeScript, JS, React | Creator of GitVersion | 🥃 ☕️ 🐶 😸

Pixel and Ink

Seven West Media (WA) Digital Team blog.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade