【问题标题】:How to test react-router-dom?如何测试 react-router-dom?
【发布时间】:2018-08-23 19:59:53
【问题描述】:
问题
我已阅读https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/testing.md
我想测试react-router-dom,我不关心它是如何工作的,我只需要确保库在我的项目样板中工作。
复制
我正在测试这个组件
<Link to="/toto">
toto
</Link>
这是测试
it('it expands when the button is clicked', () => {
const renderedComponent = mount(<Wrapper>
<MemoryRouter initialEntries={['/']}>
<Demo />
</MemoryRouter>
</Wrapper>);
renderedComponent.find('a').simulate('click');
expect(location.pathname).toBe('toto');
});
预期
成为true
结果
blank
问题
如何测试react-router-dom?
【问题讨论】:
标签:
javascript
reactjs
react-router
react-router-dom
【解决方案1】:
如果您查看Link 的代码,您会看到以下代码:
handleClick = event => {
if (this.props.onClick) this.props.onClick(event);
if (
!event.defaultPrevented && // onClick prevented default
event.button === 0 && // ignore everything but left clicks
!this.props.target && // let browser handle "target=_blank" etc.
!isModifiedEvent(event) // ignore clicks with modifier keys
) {
event.preventDefault();
const { history } = this.context.router;
const { replace, to } = this.props;
if (replace) {
history.replace(to);
} else {
history.push(to);
}
}
};
所以,大概你找到Link 而不是a 并重写此方法以将值返回给您自己的回调,您可以验证<Link> 上设置的路径,这不会直接测试react-router,而是它将验证您在链接中设置的路径是否正确,这就是您的测试似乎正在验证的内容。
类似(未经测试的代码):
const link = renderedComponent.find(Link)
let result = null
link.handleClick = event => {
const { replace, to } = link.props;
if (replace) {
result = null //we are expecting a push
} else {
result = to
}
}
};
link.simulate('click')
expect(result).toEqual('/toto') // '/toto' or 'toto'?
更新
我已经意识到上述方法不适用于浅层渲染,但是,如果您只想检查 to 属性是否正确,您可能只需使用 expect(link.props.to).toEqual('/toto') 即可。