还有这里提到,我有一个页脚组件,想要编写测试。该页脚由多个按钮组成,所有这些按钮都使用Message常量,它是一个antd弹出框组件:
编辑:我仍然被困在这个问题中。我已经使用ReactTestUtils和enzyme mount来处理了这个问题,但感觉自己深入了DOM,并且正在寻找一种不使用TestUtils的方法。
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}>
<MyButton
bounds={`${(3 * width) / 7 + (7 * width) / 84},5,${width / 7},30`}
text="CANCEL"
type="primary"
icon="close"
actionPerformed={this.cancelClicked}
/>
</Card>
actionPerformed 实际上是 onClick,它是从我的组件中作为 props 传递的。Card 是 antd 组件。
我可以非常细致地测试当单击按钮时是否调用了 cancelClicked。我想要测试,在调用 cancelClicked 并打开模态框 / 消息后,当我单击“是”(onOk)时状态是否已更改。我只想测试状态是否正确地发生了变化,尝试进行模拟和回调,但无法成功。我尝试遵循一种方法,其中模拟仅在 Message 模拟中调用 okayHandler 函数。
Footer.test
//This test works
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('MyButton[text="CANCEL"]');
p.props().actionPerformed();
expect(spy).toHaveBeenCalled();
});
//This doesn't, where I'm trying to make 'yes' clicked or 'OkayHandler' in Message called to change the state everytime modal opens
test('Footer should open a popup when cancel button is clicked, and redirect to home page', () => {
jest.mock('../../utils/uiModals', () => ({
Message: (text, okayHandler) => okayHandler(),
}));
const instance = defaultFooter.instance();
instance.cancelClicked();
expect(defaultFooter.state().from).toEqual('/home');
任何帮助都将不胜感激,我被困在如何解决这个问题上已经很长时间了。