Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

Answeredbyazurespheredev
morganm94 asked this question inQ&A
Discussion options

I have a parent component which calls a child component and pass a methodhandleIncrement via props.

I want to test theParentComponent viaJest with following steps:

  1. Mock theChildComponent viaJest

  2. Call ParentComponent'shandleIncrement method via mockedChildComponent.

Issue: How to passprops to ChildComponent and call ParentComponent method

Parent Component

    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;

Child Component

 import React from 'react'; const ChildComponent = (props) => {  return (    <button onClick={props.onIncrement}>     Increment Count    </button>  );};export default ChildComponent;

This is my Jest test file:

How to callprops.onIncrement() ?

jest.mock('ChildComponent', () => {  return {  __esModule: true,   default: () => {     const onIncrementHandler = () => {      props.onIncrement() // ==================>>>>>>  How to call this ?     }     return (       <div>         <Button id='test-button' onClick={onIncrementHandler}>Test Button</Button>       </div>      )     },   } })describe('ParentComponent', () => {  test('test button Click', async () => {   render(<ParentComponent />)   const testButton = await screen.findByTestId('test-button')   fireEvent.click(testButton)  })})
You must be logged in to vote

You need to mock theChildComponent and make sure theonIncrement prop is correctly passed and called.

  1. Mock theChildComponent in your test file.
  2. Render theParentComponent.
  3. Trigger theonIncrement function via the mockedChildComponent.

ParentComponent.js

importReact,{useState}from'react';importChildComponentfrom'./ChildComponent';constParentComponent=()=>{const[count,setCount]=useState(0);consthandleIncrement=()=>{setCount(count+1);};return(<div><ChildComponentonIncrement={handleIncrement}/><p>Count:{count}</p></div>);};exportdefaultParentComponent;

ChildComponent.js

importReactfrom'react';constCh…

Replies: 1 comment 2 replies

Comment options

You need to mock theChildComponent and make sure theonIncrement prop is correctly passed and called.

  1. Mock theChildComponent in your test file.
  2. Render theParentComponent.
  3. Trigger theonIncrement function via the mockedChildComponent.

ParentComponent.js

importReact,{useState}from'react';importChildComponentfrom'./ChildComponent';constParentComponent=()=>{const[count,setCount]=useState(0);consthandleIncrement=()=>{setCount(count+1);};return(<div><ChildComponentonIncrement={handleIncrement}/><p>Count:{count}</p></div>);};exportdefaultParentComponent;

ChildComponent.js

importReactfrom'react';constChildComponent=(props)=>{return(<buttononClick={props.onIncrement}>      Increment Count</button>);};exportdefaultChildComponent;

ParentComponent.test.js

importReactfrom'react';import{render,fireEvent,screen}from'@testing-library/react';importParentComponentfrom'./ParentComponent';// Mock ChildComponentjest.mock('./ChildComponent',()=>(props)=>(<buttondata-testid="test-button"onClick={props.onIncrement}>    Test Button</button>));describe('ParentComponent',()=>{test('increments count on button click',()=>{render(<ParentComponent/>);// Get the button and click itconsttestButton=screen.getByTestId('test-button');fireEvent.click(testButton);// Check if the count incrementedexpect(screen.getByText('Count: 1')).toBeInTheDocument();});});
You must be logged in to vote
2 replies
@morganm94
Comment options

I've got a solution. Thank you for your effort!

@vivekdShl
Comment options

You need to mock theChildComponent and make sure theonIncrement prop is correctly passed and called.

  1. Mock theChildComponent in your test file.
  2. Render theParentComponent.
  3. Trigger theonIncrement function via the mockedChildComponent.

ParentComponent.js

importReact,{useState}from'react';importChildComponentfrom'./ChildComponent';constParentComponent=()=>{const[count,setCount]=useState(0);consthandleIncrement=()=>{setCount(count+1);};return(<div><ChildComponentonIncrement={handleIncrement}/><p>Count:{count}</p></div>);};exportdefaultParentComponent;

ChildComponent.js

importReactfrom'react';constChildComponent=(props)=>{return(<buttononClick={props.onIncrement}>      Increment Count</button>);};exportdefaultChildComponent;

ParentComponent.test.js

importReactfrom'react';import{render,fireEvent,screen}from'@testing-library/react';importParentComponentfrom'./ParentComponent';// Mock ChildComponentjest.mock('./ChildComponent',()=>(props)=>(<buttondata-testid="test-button"onClick={props.onIncrement}>    Test Button</button>));describe('ParentComponent',()=>{test('increments count on button click',()=>{render(<ParentComponent/>);// Get the button and click itconsttestButton=screen.getByTestId('test-button');fireEvent.click(testButton);// Check if the count incrementedexpect(screen.getByText('Count: 1')).toBeInTheDocument();});});

Why can't we call the handleIncrement() function directly instead of cloning it's implementation, which in this case is Count: 1. Let's say there is a handler function which is executing more than one statements, for example:-
handleFunction () => { setCount(1); doThis(); doThat(); .... }

How to handle such cases?

Answer selected bymorganm94
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
3 participants
@morganm94@azurespheredev@vivekdShl

[8]ページ先頭

©2009-2025 Movatter.jp