首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何测试react-router-dom?

如何测试react-router-dom?
EN

Stack Overflow用户
提问于 2018-03-15 13:27:39
回答 1查看 1.4K关注 0票数 3

问题

我读过https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/testing.md

我想测试react-router-dom,我不关心它是如何工作的,我只需要确保库在我的项目样板中工作。

再生产

我正在测试这个组件

代码语言:javascript
复制
    <Link to="/toto">
      toto
    </Link>

这就是测试

代码语言:javascript
复制
  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

EN

回答 1

Stack Overflow用户

发布于 2018-03-15 13:56:00

如果你看一下Link的代码,你会看到这个代码:

代码语言:javascript
复制
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,但它将验证您在链接中设置的路径是否正确,这似乎是您的测试所验证的。

所以类似于(未测试代码):

代码语言:javascript
复制
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')来做。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49292154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档