There are 3 key files:
First File: utilities.js
export const utilities = () => ({
func: () => 'Function was executed',
});
Second File: AppComponent.js
import React from 'react';
import { utilities } from './utilities';
const AppComponent = () => {
const { func } = utilities();
return (
<><button onClick={func}/></>
);
};
export default AppComponent;
Third File: AppComponent.test.js
import React from 'react';
import userEvent from '@testing-library/user-event';
import { screen, render } from '@testing-library/react';
import AppComponent from './AppComponent';
import { utilities } from './utilities';
jest.mock('./utilities', () => ({
utilities: jest.fn(),
}));
test('function is called', () => {
utilities.mockImplementation(() => ({
func: jest.fn(),
}));
render(
<AppComponent />,
);
userEvent.click(screen.getByRole('button'));
expect(???????).toHaveBeenCalled();
});
This line holds the answer:
expect(???????).toHaveBeenCalled();
The query: How do I verify if the func
function was invoked? I attempted using something like expect(utilities().func)
but it didn't work as expected.