Testing if a const modal component is called

2019-07-18 20:19发布

I have a footer component which has several buttons on it. All of these buttons use the Message const, which is an antd modal :

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.

I simply want to test when the Button is clicked, cancelClicked is called. If possible, I want to test if the state changes properly when 'OK' button is clicked on the Modal. My test is as follows, but the test fails because function is not called :

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();
});

I've also tried with mount rather than shallow, but the spy is still not called.

1条回答
不美不萌又怎样
2楼-- · 2019-07-18 21:14

The "Common Gotchas" section for simulate says that "even though the name would imply this simulates an actual event, .simulate() will in fact target the component's prop based on the event you give it. For example, .simulate('click') will actually get the onClick prop and call it."

That behavior can be seen in the Enzyme source code here and here.

So the line p.simulate('click'); ends up trying to call the onClick prop of the Button which doesn't exist so it essentially does nothing.

This post from an Airbnb dev recommends invoking props directly and avoiding simulate.

In this case you would call the actionPerformed property directly like this:

p.props().actionPerformed();
查看更多
登录 后发表回答