testing-library / testing-library/react-testing-library

How to test functions inside functional component and also using hooks values

Open
#1,382 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
19.7k
Forks
1.2k
Avg merge
3d 16h
Merged PRs (30d)
1

Description

Hello

I will try to explain the case in the simplest way that I could:

I have a component: Employee.tsx

It has a pseudo code like this:

const Employee = () => {

   const { name, status } = useEmployeeDetails();
    const { updateEmployeeInfo } = useEmployeeData(();
    const { clearStorage} = useCleanData();

    const generalUpdate = async() => {
          await updateEmployeeInfo(name, status);
           clearStorage();
    }

    return(
            <>
               <span>update</update>
               <button onClick={generalUpdate}></button>
           </>
           )

}

I am trying to write a test for 'generalUpdate' function that contains async function (updateEmployeeInfo) that is using hooks data as parameters, also I want to have a way how to access or spy on this function to be able to manipulate it and test different scenarios.

So :
1- How to access a function inside a functional component.
2- how to mock this function, especially if it is using another async function in its implementation?

Basically testing a function that is using data from hooks (or using async function inside it) and it exists inside a functional component

I hope my explanation is clear 😄

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The example is in Employee.tsx and refers to useEmployeeDetails, useEmployeeData, and useCleanData, but no repository test or source path is named. Start by locating those hooks and the Employee component, then determine the user-visible behavior triggered by the update button. A concrete expected outcome and test location are needed before the work can be scoped.

Written by the indexing model from the issue text.

Assessment

Tech stack
react, typescript
Domain
frontend, testing
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.