You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
How to test functions inside functional component and also using hooks values #1382
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
@MimoJSRepo
Great question! Since generalUpdate is a function inside a functional React component, it isn't directly accessible from the test.
I'd mock the hook functions (useEmployeeDetails, useEmployeeData, useCleanData) since generalUpdate relies on them and trigger the function by simulating user interactions as a first solution.
This might help you!
jest.mock('path to useEmployeeDetails');jest.mock('path to useEmployeeData');jest.mock('path to useCleanData');test('should call updateEmployeeInfo and clearStorage on button click',async()=>{constmockUpdateEmployeeInfo=jest.fn().mockResolvedValue('success');constmockClearStorage=jest.fn();useEmployeeDetails.mockReturnValue({name: 'JD',status: 'active'});useEmployeeData.mockReturnValue({updateEmployeeInfo: mockUpdateEmployeeInfo});useCleanData.mockReturnValue({clearStorage: mockClearStorage});render(<Employee/>);constbutton=screen.getByRole('button');awaituserEvent.click(button);awaitwaitFor(()=>{expect(mockUpdateEmployeeInfo).toHaveBeenCalledWith('JD','active');});expect(mockClearStorage).toHaveBeenCalled();});
Activity
imevanc commentedon Mar 9, 2025
@MimoJSRepo
Great question! Since
generalUpdateis a function inside a functional React component, it isn't directly accessible from the test.I'd mock the hook functions (useEmployeeDetails, useEmployeeData, useCleanData) since generalUpdate relies on them and trigger the function by simulating user interactions as a first solution.
This might help you!