我有一个页脚组件,上面有几个按钮。所有这些按钮都使用Message
常量,它是一个古老的模式:
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;
Footer.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 的时间。如果可能的话,我想测试当在Modal中单击“确定”按钮时状态是否正确更改。我的测试如下,但是测试失败,因为未调用函数:
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而不是浅表,但仍未调用间谍。
答案 0 :(得分:1)
"Common Gotchas" section for simulate
说:“尽管名称暗示这将模拟实际事件,但.simulate()实际上会根据您提供的事件将组件的prop作为目标。例如,.simulate(' click')实际上会获得onClick道具并调用它。”
因此,行p.simulate('click');
最终试图调用onClick
的{{1}}道具,该道具不存在,因此实际上什么也没做。
This post建议直接调用道具,而避免使用Button
。
在这种情况下,您可以像这样直接调用simulate
属性:
actionPerformed