jonullberg
jonullberg

Reputation: 27

Testing React component with global dependency

I have included a JS dependency (Foo.js) in my index.html file. When I call Foo.js in my React component, it finds the Constructor in the global namespace and instantiates it. This works great when I deploy it, but when I go to build a test around Component.js, the test can't find Foo.js

<!--Index.html-->
<head>
<script src="Foo.js"></script>
</head>

// Component.js
var bar = new Foo(); // Works in deployment but not in Jest tests

When running my test I get this error:

RefererenceError: Foo is not defined

Now I thought I would be clever and in my Component.js file declare Foo to be window.Foo, which worked in getting rid of the undefined dependency in my Jest tests.


// Component.js
var Foo = window.Foo;
var bar = new Foo();

Suddenly my Reference error went away and I was happy. So I continue to write tests and now I get a funky error that I think has to do with that global dependency again.

TypeError: undefined is not a function

I believe that my error is still coming from Jest not properly mocking a dependency that is on the window object. I don't need to test the dependency, I just need it to be defined so I can get to writing tests for the rest of the Component. Does anyone have a thought on what I could possibly be doing wrong?

Upvotes: 0

Views: 497

Answers (1)

jonullberg
jonullberg

Reputation: 27

So I finally figured out how to fix this. In my browser environment and my testing environment I have two completely separate window objects. In my test, before I require in my component I have to set window.Foo to an anonymous function. It will look like this:


// Component.js
var bar = new Foo(); // Works in browser but not in test
// ...Rest of code

// Component.test.js
describe('Component.js', function() {
  let Component;
  beforeEach(function() {
    window.Foo = function() {};
    Component = require('./Component.js');  // When it requires in component, 
      // it will now have Foo declared on the window object
  });
});

I have to explicitly declare any window objects in my test environment for any components to find those functions.

Upvotes: 1

Related Questions