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

IT技术 reactjs react-router jestjs enzyme react-router-dom
2021-05-04 01:46:37

我有一个<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(),而不是儿童。

用户列表.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);
  });

})

用户列表.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>
    );
  }
}

联系人.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);
4个回答

要测试组件(带玩笑),其中包含<Route>withRouter需要导入路由器在您的测试,而不是在你的组件

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

并像这样使用它

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

使用上下文包裹挂载的实用函数

在测试中使用 Router 包装 mount 是可行的,但在某些情况下,您不希望 Router 成为您的挂载中的父组件。因此,我目前正在使用包装函数将上下文注入安装:

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

这可能位于 test helpers 目录中名为 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 或您自己的上下文类型。

您需要App用 aBrowserRouter或等效物包装,请参阅下面的简单测试用例示例,一个使用 React Router 的组件应用程序

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

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

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