我有一个 <UserListComponent />
,它输出一个 <Contact />
组件和联系人列表由 <Contacts />
表示。
问题是,在对 <UserListComponent />
的测试中,当我尝试挂载它时,测试输出一个错误 Invariant Violation: You should not use <Route> or withRouter() outside a <Router>
withRouter()
用于 <Contacts />
组件。
在测试父组件时,如何在没有路由器的情况下模拟 ContactsComponent
?
我发现了一些类似的问题 < a href = “ https://www.ountysource.com/questions/49297944-everant---should-not-use-router-or-withrouter-outside-a-router”rel = “ norefrer”> 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: '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);
});
})
用户列表
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);