Jest,Enzyme:Invariant Violation:你不应该在<router>之外使用<route>或withRouter()

时间:2018-04-25 15:09:46

标签: reactjs jestjs enzyme

我有一个<UserListComponent />,它会输出一个<Contact />组件和<Contacts />提供的联系人列表。

问题在于,当我尝试安装<UserListComponent />的测试时,测试输出错误Invariant Violation: You should not use <Route> or withRouter() outside a <Router>

withRouter()用于<Contacts />组件。

如何在没有路由器的情况下模拟ContactsComponent来测试父组件?

我发现了一些类似问题https://www.bountysource.com/issues/49297944-invariant-violation-you-should-not-use-route-or-withrouter-outside-a-router 但它只描述了组件由withRouter()本身覆盖的情况,而不是儿童。

UserList.test.jsx

const mockResp = {
  count: 2,
  items: [
    {
      _id: 1,
      name: 'User1',
      email: 'email1@gmail.com',
      phone: '+123456',
      online: false
    },
    {
      _id: 2,
      name: 'User2',
      email: 'email2@gmail.com',
      phone: '+789123',
      online: false
    },
    {
      _id: 3,
      name: 'User3',
      email: 'email3@gmail.com',
      phone: '+258369147',
      online: false
    }
  ],
  next: null
}

describe('UserList', () => {
  beforeEach(() => {
    fetch.resetMocks()
  });

  test('should output list of users', () => {
    fetch.mockResponseOnce(JSON.stringify(mockResp));

    const wrapper = mount(<UserListComponent user={mockResp.items[2]} />);

    expect(wrapper.find('.contact_small')).to.have.length(3);
  });

})

UserList.jsx

export class UserListComponent extends PureComponent {
  render() {
    const { users, error } = this.state;
    return (
      <React.Fragment>
        <Contact
          userName={this.props.user.name}
          content={this.props.user.phone}
        />
        {error ? <p>{error.message}</p> : <Contacts type="contactList" user={this.props.user} contacts={users} />}
      </React.Fragment>
    );
  }
}

Contacts.jsx

class ContactsComponent extends Component {
  constructor() {
    super();
    this.state = {
      error: null,
    };
  }

  render() {
    return (
      <React.Fragment>
        <SectionTitle title="Contacts" />
        <div className="contacts">
         //contacts
        </div>
      </React.Fragment>
    );
  }
}

export const Contacts = withRouter(ContactsComponent);

7 个答案:

答案 0 :(得分:45)

要测试包含<Route>withRouter的组件(使用Jest),您需要在测试中导入路由器,而不是在组件中导入

import { BrowserRouter as Router } from 'react-router-dom';

并像这样使用

app = shallow(
    <Router>
        <App />
    </Router>);

答案 1 :(得分:17)

使用上下文包装挂载的实用程序功能

在测试中使用路由器包装挂载有效,但有些情况下您不希望路由器成为挂载中的父组件。因此,我正在使用包装函数将上下文注入mount:

import { BrowserRouter } from 'react-router-dom';
import Enzyme, { shallow, mount } from 'enzyme';

import { shape } from 'prop-types';

// Instantiate router context
const router = {
  history: new BrowserRouter().history,
  route: {
    location: {},
    match: {},
  },
};

const createContext = () => ({
  context: { router },
  childContextTypes: { router: shape({}) },
});

export function mountWrap(node) {
  return mount(node, createContext());
}

export function shallowWrap(node) {
  return shallow(node, createContext());
}

这可能位于测试帮助程序目录中名为contextWrap.js的文件中。

示例描述块:

import React from 'react';
import { TableC } from '../../src/tablec';
import { mountWrap, shallowWrap } from '../testhelp/contextWrap';
import { expectedProps } from './mockdata'

describe('Table', () => {
  let props;
  let component;
  const wrappedShallow = () => shallowWrap(<TableC {...props} />);

  const wrappedMount = () => mountWrap(<TableC {...props} />);

  beforeEach(() => {
    props = {
      query: {
        data: tableData,
        refetch: jest.fn(),
      },
    };
    if (component) component.unmount();
  });

  test('should render with mock data in snapshot', () => {
    const wrapper = wrappedShallow();
    expect(wrapper).toMatchSnapshot();
  });

  test('should call a DeepTable with correct props', () => {
    const wrapper = wrappedMount();
    expect(wrapper.find('DeepTable').props()).toEqual(expectedProps);
  });

});

您还可以使用此模式将子组件包装在其他类型的上下文中,例如,如果您使用的是react-intl,material-ui或您自己的上下文类型。

答案 2 :(得分:3)

您需要用App或等效符号包装BrowserRouter, 请参阅下面的简单测试案例示例,其中是使用React Router的组件App

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";

it("renders without crashing", () => {
  const div = document.createElement("div");
  ReactDOM.render(
<BrowserRouter>
  <App />
</BrowserRouter>,
div
  );
  ReactDOM.unmountComponentAtNode(div);
})

答案 3 :(得分:3)

A将“ URL”的历史记录保留在内存中(不读取或写入地址栏)。在测试和非浏览器环境(例如React Native)中很有用。

我得到了类似的错误解决方案,是在Memory router的帮助下包装了组件

import { MemoryRouter } from 'react-router'

<MemoryRouter>
  <App/>
</MemoryRouter>

答案 4 :(得分:1)

实际上,我曾经使用react-test-renderer为我的组件创建快照测试,并且遇到了这个问题,我只是用BrowserRouter附带的react-router-dom包装了我的组件,您可以像下面这样:

import React from 'react'
import { BrowserRouter } from 'react-router-dom'
import renderer from "react-test-renderer";


import UserListComponent from './whatever'



test('some description', () => {
  
  const props = { ... }

  const jsx = (
    <BrowserRouter>
      <UserListComponent {...props} />
    </BrowserRouter>
  )

  const tree = renderer.create(jsx).toJSON()
  expect(tree).toMatchSnapshot()

})

如果要多次测试,完全建议在这种情况下使用测试工厂!

答案 5 :(得分:1)

添加路由器标签以呈现它。

import * as React from "react";
import { render, mount } from 'enzyme';
import { BrowserRouter as Router } from "react-router-dom"
import CategoriesToBag from "../CategoriesToBag";



describe('Testing CategoriesToBag Component', () => {
    test("check if heading is correct", () => {
        const defaultValue = "Amazing Categories To Bag";
        const wrapper = render(<Router><CategoriesToBag /></Router>);
        expect(wrapper.find('.textBannerTitle').text()).toMatch(/Categories To Bag/);
        expect(wrapper.find('.textBannerTitle').text()).not.toMatch(/Wrong Match/);
        expect(wrapper.find('.textBannerTitle').text()).toBe(defaultValue);
    });

});

你应该没事了。

答案 6 :(得分:0)

我遇到了同样的问题,第一个注释对我有所帮助,但是有很多代码 我有更好的方法来解决这个问题。 请参阅下面的解决方案:

    import React from 'react';
import { shallow, mount } from 'enzyme';
import SisuSignIn from '../../../components/Sisu/SisuSignIn.js';
import { MemoryRouter } from 'react-router-dom';

const Container = SisuSignIn;

let wrapper;

beforeEach(() => {
  wrapper = shallow(<Container />);
});

describe('SisuSignIn', () => {
  it('renders correctly', () => {
    expect(wrapper).toMatchSnapshot();
  });
  it('should render one <h1>', () => {
    const wrapper = mount(
      <MemoryRouter>
        <SisuSignIn auth={{ loading: false }} />
      </MemoryRouter>
    );
    expect(wrapper.find('div').length).toBe(12);
  });
});