Javascript 如何测试路由器dom? 问题
我读过 我想测试Javascript 如何测试路由器dom? 问题,javascript,reactjs,react-router,react-router-dom,Javascript,Reactjs,React Router,React Router Dom,我读过 我想测试react router dom,我不关心它是如何工作的,我只需要确保库正在我的项目样板中工作 繁殖 我正在测试这个组件 <Link to="/toto"> toto </Link> 托托 这就是测试 it('it expands when the button is clicked', () => { const renderedComponent = mount(<Wrapper>
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');
});
it('单击按钮时它会展开',()=>{
const renderedComponent=mount(
);
renderedComponent.find('a').simulate('click');
expect(location.pathname).toBe('toto');
});
预期
为true
结果
空白
问题:
如何测试
react路由器dom
?如果查看链接的代码,您会看到以下代码:
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);
}
}
};
因此,您可能会找到链接
,而不是a
,并重写此方法以向您自己的回调返回一个值。您可以验证
上设置的路径,这不会直接测试react路由器,但它会验证您在链接中设置的路径是否正确,而这正是您的测试所要验证的
比如(未经测试的代码):
更新
我已经意识到,上面的方法不适用于浅层渲染,但是,如果您只想检查to
属性是否正确,您可能只需要使用expect(link.props.to).toEqual('/toto')
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'?