问题
我想测试 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');
});
预期
要真实
结果
空白
问题
如何测试 react-router-dom
?
最佳答案
如果您查看 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')
来做到这一点.
关于javascript - 如何测试react-router-dom?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49292154/