使用MemoryRouter时如何知道当前URL

时间:2018-09-26 15:30:50

标签: reactjs testing react-router

我正在尝试找出如何使用测试来断言当前位置路径名是什么。

作为实验and based on some docs,我编写了以下测试

  test(`Can navigate MemoryRouter`, (done) => {
    const logAll = (p, ...args) => {
      console.log(`SOME OUTPUT`,p, ...args)
      return p.location.pathname
    }

    const div = document.createElement('div')

    const Test = () => (
      <MemoryRouter>
        <React.Fragment>
          <Link to="/foo/bar" id="click-me" />
          <Route render={logAll} />
        </React.Fragment>
      </MemoryRouter>
    )
    ReactDOM.render(React.createElement(Test), div)
    console.log('click')
    Simulate.click(div.querySelector('#click-me'))
  })

我希望如此,因为logAll路由会匹配所有更改,以使其在/处记录一次(它确实记录),然后在/foo/bar处记录一次。但是后者永远不会在测试超时(约5秒)之前记录日志。

我想念什么?

1 个答案:

答案 0 :(得分:1)

您的测试还可以(您甚至不需要done),但是错过了Simulate.click的第二个参数。如果添加它,它将按预期工作:

Simulate.click(
    div.querySelector('#click-me'),
    { button: 0 }
);

查看the codebase表明Link不会继续进行没有button=0事件的点击。

Blame of this line,显示Link tracks only left button click