rk919
rk919

Reputation: 317

How to access the history object in Jest

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;
}

Upvotes: 7

Views: 25795

Answers (2)

Bart
Bart

Reputation: 6814

This worked for my scenario, which seems similar to yours.

beforeAll(() => {
  window.history.replaceState({query: 'google'}, 'MOCK');
});

Upvotes: 2

user3586413
user3586413

Reputation:

You need to use createMemoryStore to mock history like this:

import React from 'react'
import { shallow } from 'enzyme'
import { createMemoryHistory } from 'history'

import Page from '../Page'

describe('<Page />', () => {
  it('should render correctly', () => {
    const history = createMemoryHistory('/dashboard')
    const renderedComponent = shallow(
      <Page history={history} />
    )
    expect(renderedComponent).toMatchSnapshot()
  })
})

References:

Upvotes: 17

Related Questions