我如何测试包裹在用withRouter中的反应组件的回调



我正在使用开玩笑和酶来测试用打字稿编写的React项目。我的组件包裹在一个反复路由器中,看起来有点像这样:

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 Prop是未定义的。但是,当我输出page时,它确实说明了它是定义的:

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

以及下面的一些行:

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

SomeButtonwithRouter(SomeButton)均无法作为酶find的选择器。

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

grr ...像往常一样,睡个好觉可以帮助我发现问题 - 实际上并不是在这里。如果它帮助任何人,我将详细介绍我犯的错误。

首先,最有用的事情要知道: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()进行跟进。哦,还有:之后我的断言中有一个错别字。

我知道,愚蠢。六个月内遇到这个问题时,请随时嘲笑我。

最新更新