如何在Jest中访问历史对象

rk9*_*919 5 reactjs jestjs enzyme

我有一个if条件,看起来像这样:

if (history.state !== null && history.state.query)
Run Code Online (Sandbox Code Playgroud)

问题是,虽然这在Jest中不起作用,但history在我的测试中是一个空对象.

在我的测试中需要做什么才能使用该history对象?我在Node.js服务器上使用React运行它.不确定这是否重要,但我也在使用React Router.

测试用例:

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
});
Run Code Online (Sandbox Code Playgroud)

部分组件(不能放整个组件):

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;
}
Run Code Online (Sandbox Code Playgroud)

nif*_*uce 13

你需要使用createMemoryStore这样的模拟history:

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()
  })
})
Run Code Online (Sandbox Code Playgroud)

参考文献: