【问题标题】:Mock basename in Jest / EnzymeJest / Enzyme 中的模拟基本名称
【发布时间】:2018-06-04 19:01:00
【问题描述】:

我的历史课看起来像:

import createHistory from 'history/createBrowserHistory';

export default createHistory({
  basename: '/admin/',
});

当针对连接到商店并使用路由器呈现的类编写/运行任何单元测试时,我在测试中收到以下警告:

console.error node_modules/warning/warning.js:51
  Warning: You are attempting to use a basename on a page whose URL path does not begin with the basename. Expected path "blank" to begin with "/admin".

一个示例测试如下:

import React from 'react';
import { MemoryRouter as Router } from 'react-router-dom';
import { mount } from 'enzyme';
import configureStore from 'redux-mock-store';
import TenantListContainer from '../../../src/containers/TenantList';
import TenantList from '../../../src/containers/TenantList/TenantList';

const mockStore = configureStore();
const store = mockStore({
  tenants: {
    tenants: ['foo'],
    loading: true,
  },
});


describe('TenantListContainer', () => {
  it('should render the TenantList components', () => {
    const wrapper = mount(
      <Router>
        <TenantListContainer store={store} />
      </Router>
    );
    expect(wrapper.find(<TenantList />)).toBeTruthy();
  });
});

如何使用 MemoryRouter 模拟这个历史道具? 我尝试过传入历史对象,但是我被告知内存路由器忽略了这个道具。

【问题讨论】:

    标签: reactjs unit-testing jestjs enzyme


    【解决方案1】:

    你总是可以从你的 Jest 配置中模拟出 url。

    我的方法通常是将其包含在我的package.json

    在你的情况下,我希望这类似于 -

     "jest": {
        "testURL": "http://some-domain.tld/admin"
      }
    

    然后您可以通过在 beforeEach() 块中包含以下内容来根据每个测试更改此设置

    window.history.pushState({}, 'Foo Title', '/admin/foo');
    

    【讨论】:

      【解决方案2】:

      对于使用 create-react-app 的用户:更新 package.json 并在测试命令行末尾添加 url,如下所示:

      react-scripts-ts test --env=jsdom --watch --testURL http://localhost/foo
      

      来源:https://github.com/facebook/create-react-app/issues/3425

      【讨论】:

        【解决方案3】:

        您需要为jest 设置正确的testURL。这是在jest.config.js 中完成的,例如这样:

        module.exports = {
          ...
          testURL: 'http://localhost/admin',
        }
        

        【讨论】:

          猜你喜欢
          • 2019-08-28
          • 2019-01-29
          • 2018-03-28
          • 2020-02-02
          • 2019-05-12
          • 2019-10-27
          • 2019-08-12
          • 2022-01-19
          • 2019-11-18
          相关资源
          最近更新 更多