Skip to content

React Testing using Jest : How to call parent methods passed to Mocked Child Component via props #651

Answered by azurespheredev
morganm94 asked this question in Q&A
Discussion options

You must be logged in to vote

You need to mock the ChildComponent and make sure the onIncrement prop is correctly passed and called.

  1. Mock the ChildComponent in your test file.
  2. Render the ParentComponent.
  3. Trigger the onIncrement function via the mocked ChildComponent.

ParentComponent.js

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const [count, setCount] = useState(0);

  const handleIncrement = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <ChildComponent onIncrement={handleIncrement} />
      <p>Count: {count}</p>
    </div>
  );
};

export default ParentComponent;

ChildComponent.js

import React from 'react';

const Ch…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@morganm94
Comment options

Answer selected by morganm94
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants