问题
我想测试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
发布于 2018-03-15 13:56:00
如果你看一下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')来做。
https://stackoverflow.com/questions/49292154
复制相似问题