首页 > 解决方案 > Jest, Enzyme: Invariant Violation: 你不应该使用或 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);

标签: reactjsreact-routerjestjsenzymereact-router-dom

解决方案


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

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

并像这样使用它

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

推荐阅读