gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:59:39 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com