开玩笑,酶:不变违规:您不应该在 <Router> 之外使用 <Route> 或 withRouter()

新手上路,请多包涵

我有一个 <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);

原文由 Maryja Piaredryj 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 583
1 个回答

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

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

并像这样使用它

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

原文由 Edhar Dowbak 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进