JS: Overriding global variables when testing

This example is thought of with React and Tape.

I was met with this issue, and was not completely sure how to address it, and didn't really find anything online, maybe it's too clear for some people, but it wasn't for me.

Let's say you're getting some information rendered in the server as global variables that you need, for example the CSRF token.

So you get a rendered HTML that looks something like this:

  <div id="root">
    var INFO = { has_feature: <%= has_feature %> };

And you are hiding elements in your component according to this variable.


import { has_feature } from 'INFO';

export default class MyComponent extends Component {  

  render() {
     if (has_feature) {
     } else {
       return 'You don\'t have this feature';

And now that you are writing tests for your components you want to make sure that this actually happens.

In your test configuration file, on in your webpack config you can set the feature as available by default by listing that variable as an external: https://webpack.github.io/docs/configuration.html#externals
So when you are running the tests the feature is on.


import test from 'tape';  
import has_feature from 'INFO';

test("it renders correctly when the feature is available", t => {  
  const wrapper = ...

test("it renders correctly when the feature is NOT available", t => {  
  has_feature = false;
  const wrapper = <MyComponent />
  // After you have done your tests you need to set this back, in case you want to keep testing things about the feature, and just to bring it back to its original value.
  has_feature = true;

I know this is not the prettiest way to do it, if you're using mocha you can wrap this in a beforeEach and afterEach block so you can separate your tests by when the feature is available and when the feature is not available.