我有一个<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: '[email protected]',
      phone: '+123456',
      online: false
    },
    {
      _id: 2,
      name: 'User2',
      email: '[email protected]',
      phone: '+789123',
      online: false
    },
    {
      _id: 3,
      name: 'User3',
      email: '[email protected]',
      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);

最佳答案

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

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

像这样使用
app = shallow(
    <Router>
        <App />
    </Router>);

09-25 17:37