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