reactjs - 如何测试包含在 withRouter 中的 React 组件的回调?

标签 reactjs typescript react-router jestjs enzyme

我正在使用 Jest 和 Enzyme 来测试用 TypeScript 编写的 React 项目。我有一个包裹在 React-Router 路由器中的组件,它看起来有点像这样:

import { SomeButton } from './someButton';
import { RouteComponentProps, withRouter } from 'react-router';

const SomeButtonWithRouter = withRouter<{buttonCallback: () => void}>(SomeButton);

export class SomePage extends React.Component <RouteComponentProps<{}>, {}> {
  constructor(props: {}) {
    super(props);

    this.someCallback = this.someCallback.bind(this);
  }

  public render() {
    return (
      <div>
        <SomeButtonWithRouter buttonCallback={this.someCallback}/>
      </div>
    );
  }

  // This is the callback I want to  test:
  private someCallback() {
    console.log('This is a callback');
  }

现在我正在尝试编写一个调用 someCallback 的测试,然后进行一些断言。我将 SomePage 包装在 MemoryRouter 中以便能够对其进行测试:

it('should do something', () => {
  const page = mount(<MemoryRouter><SomePage/></MemoryRouter>);
  const cb = page.find('SomeButton').prop('buttonCallback'); // <-- this is undefined
});

如评论中所述,不幸的是 buttonCallback 属性在这样访问时未定义。但是,当我输出 page 时,它确实说它已定义:

<withRouter(SomeButton)
  onVerified={[Function bound ]}

和下面的几行:

<SomeButton
  history={ // ...
  // ...
  onVerified={[Function bound ]}

SomeButtonwithRouter(SomeButton) 都不能用作 Enzyme 的 find 的选择器。

我不确定为什么会这样;我能够以这种方式访问​​另一个未包装在 withRouter 中的子组件的回调。我也不确定我所做的一切是否首先是正确的方法,因此欢迎任何关于更好的做事方法的指示。

最佳答案

Grr... 和往常一样,一夜的 sleep 帮助我确定了问题所在 - 但问题实际上并不在这里。如果它对任何人有帮助,我将详细说明我所犯的错误。

首先,要知道最有用的东西:const cb = page.find('SomeButton').prop('buttonCallback');const cb = page. find('withRouter(SomeButton)').prop('buttonCallback'); 应该可以工作 - 虽然我会选择前者,因为那样你就不需要知道路由器的使用了。

其次,我认为它不起作用的原因是因为我试图使用 toJson(page.find('SomeButton').prop('buttonCallback')) (使用 enzyme-to-json ),它会很乐意将该函数转换为 undefined

最后,这是最愚蠢的事情 - 我没有看到调用回调的效果,因为......我实际上并没有调用它。我只是给它分配了 const buttonCallback = page.find...,但必须跟进 buttonCallback()。哦,还有:我之后的断言中有一个错字。

我知道,笨蛋。当你在六个月内遇到这个问题时,请随意 mock 我。

关于reactjs - 如何测试包含在 withRouter 中的 React 组件的回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46541756/

相关文章:

TypeScript:根据另一个字段查找字段的类型

javascript - 在 React/Redux 中更改 url

javascript - 打印预览中的第一页后模态内容被 chop

javascript - Protractor :非 Angular 应用程序中的多个浏览器实例:ignoreSynchronization 不起作用

javascript - 不同的子组件同时调用 setState 会弄乱父组件的状态

javascript - "Uncaught TypeError: history.push is not a function"发生错误

javascript - 推送新 URL 时,React 组件渲染会被多次调用

reactjs - 使用具有另一个来源的 API (CORS) 来响应应用程序

angular - 如何忽略 typescript 或 idm 错误?

javascript 将数组合并为单个对象