我有一个页脚组件,上面有几个按钮。所有这些按钮都使用 Message
常量,这是一个 antd 模态:
Message.jsx
import { Modal } from 'antd';
const { confirm } = Modal;
export const Message = (text, okayHandler, cancelHandler) => {
confirm({
title: text,
okText: 'Yes',
cancelText: 'No',
onOk: okayHandler,
onCancel: cancelHandler,
});
};
export default Message;
页脚.jsx
class Footer extends Component {
state = {
from: null,
redirectToReferrer: false,
};
cancelClicked = () => {
Message('Return to the previous screen?', () => {
this.setState({ redirectToReferrer: true, from: '/home' });
});
};
render() {
const { redirectToReferrer, from } = this.state;
if (redirectToReferrer) {
return <Redirect to={{ pathname: from }} />;
}
return (
<Card style={footerSyles}>
<Button
bounds={`${(3 * width) / 7 + (7 * width) / 84},5,${width / 7},30`}
text="CANCEL"
type="primary"
icon="close"
actionPerformed={this.cancelClicked}
/>
</Card>
//actionPerformed is actually onClick, it's taken as a prop from my <Button /> component. Card is an antd component while button is not.
我只是想测试当点击Button 时,cancelClicked 被调用。如果可能的话,我想测试在模态上单击“确定”按钮时状态是否正确更改。我的测试如下,但是因为没有调用函数,所以测试失败了:
Footer.test
const defaultFooter = shallow(<Footer position="relative" bounds="10,0,775,100" />);
test('Footer should open a popup when cancel button is clicked, and redirect to home page', () => {
const instance = defaultFooter.instance();
const spy = jest.spyOn(instance, 'cancelClicked');
instance.forceUpdate();
const p = defaultFooter.find('Button[text="CANCEL"]');
p.simulate('click');
expect(spy).toHaveBeenCalled();
});
我也试过使用 mount 而不是 shallow,但是 spy 仍然没有被调用。
最佳答案
"Common Gotchas" section for simulate
说“即使名称暗示这模拟了一个实际事件,.simulate() 实际上会根据您给它的事件定位组件的 Prop 。例如,.simulate('click') 实际上会获得 onClick Prop 并调用它。”
可以在 Enzyme
源代码中看到该行为 here和 here .
因此 p.simulate('click');
行最终尝试调用 Button
的 onClick
属性它不存在,所以它基本上什么都不做。
This post来自 Airbnb 开发者的建议直接调用 props 并避免 simulate
。
在这种情况下,您可以像这样直接调用 actionPerformed
属性:
p.props().actionPerformed();
关于reactjs - 测试是否调用了 const 模态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53295027/