【问题标题】:How to access the history object in Jest如何在 Jest 中访问历史对象
【发布时间】:2019-07-10 17:45:40
【问题描述】:

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

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

问题在于,虽然这在 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
});

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

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

【问题讨论】:

  • 你使用什么版本的 react-router?你是否从组件中的 props 中检索历史记录?
  • 那么您可以通过将state.query 添加到空对象来模拟history 吗?
  • @hinok 我使用来自window 的全局history。我相信版本是3.0.2
  • @VincentTaing 我试过模拟,但是当我模拟时没有用global.window = {history:{state:{query:"..."}}};我应该以不同的方式模拟它吗?
  • @RaDeuX 你能告诉我们你要测试的组件和测试用例吗?

标签: reactjs jestjs enzyme


【解决方案1】:

您需要像这样使用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()
  })
})

参考资料:

【讨论】:

    【解决方案2】:

    这适用于我的场景,看起来与你的相似。

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

    【讨论】:

    • 就我而言,我必须插入第二个参数才能使其工作,window.history.replaceState({query: 'google'}, null, 'MOCK');
    猜你喜欢
    • 2017-08-23
    • 1970-01-01
    • 2021-05-13
    • 2017-08-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多