简体   繁体   中英

simulate child component element click in parent component test file

I couldn't find a way to simulate the click of an element exists in child component from parent test file.

let card;

const displayCardSection = (cardName) => {
  card = cardName;
};

describe('Parent component', () => {
  it('simulate click event on child link', () => {
    const component = mount(<Parent
    />);
    const res = component.find(<Child
        onLinkClick={displayCardSection(CM_CARD)}
    />);
    expect(res).toBeDefined();
    res.exists('#cm_link').simulate('click');
    expect(card).toBe(CM_CARD);
  })
})

This is the test file of a parent component.

Parent.jsx:

class Parent extends Component {

  handleClick = () => {
    console.log('link clicked!');
  };

  render() {

    const linkText = 'Link'
    return (
      <Child 
        linkText={linkText}
        onLinkClick={handleClick}
      />
    );
  }
}

Child.jsx:

function Child({linkText, onLinkClick}) {
  return (
    <Link id="cm_link" onClick={onLinkClick}>{linkText}</Link>
    );
}

These are the components that I have.

I expect to simulate the link click of a child component from parent and the output should be the card displayed is 'CM_CARD'. I can write an assert statement but I'm not to simulate a click event of an element which exists in child but event handled in parent itself.

First I would suggest using shallow and the code will be the following:

const component = shallow(<Parent />);

// The following code should trigger the handler and then you will see the console output 
component.find("Child").prop("onLinkClick")();

I hope this is useful and will solve your problem, Have a good day!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM