Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何测试路由器dom? 问题_Javascript_Reactjs_React Router_React Router Dom - Fatal编程技术网

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'?