← Blog

How to handle global objects, injected by a CDN in Jest/Enzyme/TypeScript?

January 30, 2019

Whether you’re using Stripe, Facebook Pixel, Paylike, etc you might be forced into loading external JavaScript into your app via CDN.

This is the situation i was in when i tried to use the Paylike SDK, where i had to import it through their CDN. It would look a little something like this:

<script src="https://sdk.paylike.io/3.js"></script>
<script>const paylike = Paylike('your key');</script>

Great! So let’s start making some components and writing tests for them! Writing the components works fine, but when running unit tests i kept getting this error:

ReferenceError: Paylike is not defined

How do Jest and Enzyme handle external libraries?

They don’t.

So how can i write test?

You need to go into your enzyme setup file and add a Paylike key to the global object and an arrow function as a value.

You might try to do like this:

global.Paylike = () => ({});

This might not work, depending on your TypeScript rules, because editing the global object can be forbidden.

If you can’t change the rules you can do this (add the disable rule if necessary):

// tslint:disable-next-line:no-string-literal
global['Paylike'] = () => ({});

No bueno?

An alternative would be to use Jest’s beforeAll to add the missing variables to the global scope and then deleting them with the afterAll method to clean up your changes to global.

Once the missing key is added you can carry on testing as usual.

Sai Krishna

Written by Boris Yordanov.

Psst! Wanna hire me?

Here's my resume