gpt4 book ai didi

reactjs - 开 Jest , enzyme : Invariant Violation: You should not use or withRouter() outside a

转载 作者:行者123 更新时间:2023-12-03 12:56:25 27 4
gpt4 key购买 nike

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

})

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> 的组件(使用 Jest)和withRouter您需要在测试中导入 Router,而不是在组件中导入 Router

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

像这样使用它

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

关于reactjs - 开 Jest , enzyme : Invariant Violation: You should not use <Route> or withRouter() outside a <Router>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50025717/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com