我有一个页脚组件,上面有几个按钮。所有这些按钮都使用Messageconst,它是一个 antd 模式:
消息.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被调用。如果可能,我想测试在模态上单击“确定”按钮时状态是否正确更改。我的测试如下,但测试失败,因为没有调用函数:
页脚测试
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 而不是浅,但仍然没有调用 spy。