How to access the history object in Jest

Viewed 23334

I have an if conditional that looks like this:

if (history.state !== null && history.state.query)

The issue is that while this doesn't work in Jest, as history is an empty object in my tests.

What needs to be done in my tests to use the history object? I'm running this using React on a Node.js server. Not sure if this matters, but I'm also using React Router.

Test case:

beforeEach(() => {
  window.ga = jest.fn();
  window.analytics = jest.fn();
  window.analytics.track = jest.fn();
});

it('should set up props from history state', () => {
  let location = {
    pathname: '/explore',
    query: {
      query: 'yahoo',
    },
  };

  global.history = { state: { query: 'google'} };

  const wrapper = mount(
    <LandingPage location={location} />
  );

  console.log("global.history.state: " + global.history.state); // prints null
});

Part of the component (can't put the whole component):

if (props.location && props.location.pathname === '/explore') {
  explorePath = true;
  skipIntro = true;
  explore = true;

  /* checks if history.state is not equal to null
   * if check passes, search query and results will appear
   */
  if (history.state !== null && history.state.query) {
    currentValue = history.state.query;
    employeeMin = history.state.eMin;
    employeeMax = history.state.eMax;
    revenueMin = history.state.rMin;
    revenueMax = history.state.rMax;
  }
} else {
  explore = skipIntro;
}
2 Answers
Related