使用 Link 测试子组件:“<Link>s 在路由器上下文之外呈现无法导航。”

Testing a sub-component with a Link: '<Link>s rendered outside of a router context cannot navigate.'

我有一个创建 react-router Link 元素的按钮组件。它还允许传入 onClick 函数以实现其他功能(例如发送 Google Analytics 事件)。

我已将此组件包含在父组件中,如下所示:

export default class Page extends Component {
   const doSomething = () => {
    //do a thing to test here
   }

   return (
      <div>
         <Button
            onClickFn{() => doSomething()}
            linkToUrl='/other/page' //this creates a <Link> inside the button
          />
      </div>
   )
}

当我想测试 doSomething 是否被正确触发时,问题就来了。我使用 Enzyme mount 创建了包含按钮的测试 Page 组件。当我模拟点击时出现以下错误

 '<Link>s rendered outside of a router context cannot navigate.'

因为按钮中的 Link 没有上下文。有没有办法嘲笑这个或防止错误显示?或者是否有更好的方法来测试此功能?

在您的测试中,您需要在 <Router> 内渲染组件。您可以查看 tests for the <Link> component 以获取有关如何执行此操作的示例。

基本思想是创建一个内存历史实例,将其传递给 <Router>,然后在传递给它的 <Route> 中渲染 <Link>。听起来有点复杂,其实很简单

import { createMemoryHistory } from 'history'

it('clicks', () => {
  const history = createMemoryHistory()
  const App = () => (
    <Router history={history}>
      <Route path='/' component={Page} />
    </Router>
  )
})

基于 Paul 的回答,这里有一个更详细的示例,用于测试 ButtononClick(或者更准确地说,它的 Link 子级)。该示例使用测试库 mocha(BDD 测试运行程序)、chai(BDD 断言)、enzyme(React 测试实用程序)和 sinon(测试替身)。

import React from 'react';
import { Router, Route } from 'react-router';
import { createMemoryHistory } from 'history';

import MyCustomPage from '/.index';

describe('MyCustomPage', function(){
  it('stores data when clicking the link', function() {
    // Arrange
    const Page = () => (
      <MyCustomPage foo="foo" bar="bar" />
    );

    const container = enzyme.mount(
      <Router history={createMemoryHistory()}>
        <Route path="/" component={Page} />
      </Router>
    );

    // Act
    container.find('#my-link').simulate('click');

    // Assert
    expect(sessionStorage.setItem).to.have.been.calledWith('key', 'value');
  });
});