reactjs - Jest/Enzyme 中的模拟基本名称

标签 reactjs unit-testing jestjs enzyme

我有一个历史课,如下所示:

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 模拟这个历史记录? 我尝试传递历史对象,但随后我被告知内存路由器会忽略此 Prop 。

最佳答案

您始终可以从 Jest 配置中模拟出 URL。

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

就你而言,我希望这会是这样的 -

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

然后,您可以通过在 beforeEach() block 中包含以下内容,在每次测试的基础上更改此设置

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

关于reactjs - Jest/Enzyme 中的模拟基本名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47936167/

相关文章:

reactjs - 使用 react-testing-library 测试样式化的组件

c++ - libpq - 编写测试

reactjs - react 测试错误

javascript - JEST 错误 TypeError : specificMockImpl. apply is not a function

javascript - 如何将 Create-React-App 构建推送到 Heroku?

reactjs - React redux - 将多个项目添加到状态树对象中的数组的问题

python - 单元测试 Python : how to modify a source code by adding comments and decorators

unit-testing - Controller 在单元测试下返回空的contentAsString

javascript - 开 Jest : How to mock one specific method of a class

html - 我的图标在桌面和开发工具上看起来不错,但在 iPhone 上就被弄脏了