Boris Yordanov
Boris Yordanov's Blog


Boris Yordanov's Blog


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

Boris Yordanov's photo
Boris Yordanov
·Jan 30, 2019·

2 min read

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=""></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 a 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 delete 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.

Share this