【发布时间】:2019-04-21 14:26:28
【问题描述】:
还解决了here,我有一个页脚组件,我正在尝试为其编写测试。页脚由几个按钮组成。所有这些按钮都使用 Message const,这是一个 antd modal :
编辑:我仍然陷入这个问题。我已经设法用 ReactTestUtils 和酶安装来解决这个问题,但我觉得我在 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,它是我组件中的一个道具。 Card是一个antd组件。
我可以测试当按钮被点击得很细时是否调用了 cancelClicked。我想测试,在调用 cancelClicked 并且模式/消息已打开后,当我单击“是”(onOk)时,状态是否已更改。我只想测试状态是否正确更改,尝试进行模拟和回调但无法做到。我尝试遵循一种方法,即 mock 只在 Message mock 中调用 OKHandler 函数。
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');
任何帮助将不胜感激,我在很长一段时间内都被困在如何解决这个问题上。
【问题讨论】:
标签: javascript reactjs testing jestjs enzyme