reactjs - 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);
解决方案
要测试包含的组件(使用 Jest),<Route>
您withRouter
需要在测试中导入路由器,而不是在您的组件中
import { BrowserRouter as Router } from 'react-router-dom';
并像这样使用它
app = shallow(
<Router>
<App />
</Router>);
推荐阅读
- android - 观察房间实体中嵌套列表的变化
- tensorflow - Tensorflow 错误:“ValueError:没有为任何变量提供梯度”
- ethereum - 交易因错误退出(状态 0)
- java - Spring @Transactional 何时锁定数据库表行
- javascript - 如何在传单中标准化属性并动态分配 fillColor 变量
- url - AudioInputStream 正在抛出 NullPointerException
- entity-framework - 如何为多个拥有的导航属性使用相同的数据库表,这些导航属性是与 EF Core 相同类型的集合?
- triggers - 创建相关对象时如何使用触发器将复选框设置为true
- java - 没有 FXML 文件的 JavaFX Scene Builder 替代方案
- excel - VBA - 重命名文件