1

In my Rails project, I am using the react-rails gem, which does the following:

window.React = React;

This is pretty handy, but when I run unit tests using Jest, that global is not there and I get an error from the file containing the component I am testing saying that React is not defined.

If I define React in the component file using

import React from 'react';

Then it causes errors due to loading React twice.

How should I define a global React variable in my unit tests so they work?

Matt Gibson
  • 14,616
  • 7
  • 47
  • 79
  • maybe this is helpful? http://stackoverflow.com/questions/30233357/jest-react-how-to-use-global-object-in-unit-tests – jnes Jan 11 '16 at 12:07
  • Thanks. Trying it, but not luck yet. – Matt Gibson Jan 11 '16 at 12:30
  • are you using webpack or babel? For you could set up a if/else branch to include the import line. [See this example with babel](https://babeljs.io/docs/plugins/transform-inline-environment-variables/) – enjoylife Jan 12 '16 at 01:28

1 Answers1

0

In your test file, do:

import React from 'react'

describe('something',() => {
  window.React = React
  // so when you require() your component, window.React is already set
  var MyComponent = require('MyComponent').default

  it('does something', () => {
    // do something
  })
})
Shiva Nandan
  • 1,835
  • 1
  • 13
  • 11