I am new to React/TypeScript and need help with my unit testing. I need full line coverage for the code in ReactErrorBoundary.tsx but my test is not able to correctly mock the objects.
ReactErrorBoundary.tsx:
export default function ReactErrorBoundary(props: { readonly children?: ReactNode }) {
return (
<ErrorBoundary
FallbackComponent={ErrorPage}
onError={(error) => {
console.log("Error caught!");
logger(error)
}}
onReset={() => {
console.log("reloading the page...");
window.location.reload();
}}
>
{props.children}
</ErrorBoundary>
);
}
This is my logger (logService.tsx):
export const logger = (message: any) => {
console.log("This is the logger service " +
(message?.message ? message.message : message));
}
These are the tests I have so far, in which only the first two pass:
import ReactErrorBoundary from '../../components/ReactErrorBoundary';
import { ErrorBoundary } from 'react-error-boundary';
import { logger } from '../../services/logService';
import ErrorPage from '../../components/ErrorPage';
jest.mock('../../services/logService', () => ({
logger: jest.fn(),
}));
jest.mock('react-error-boundary', () => {
const React = require('react');
const ErrorPage = require('../../components/ErrorPage').default;
return {
...jest.requireActual('react-error-boundary'),
ErrorBoundary: jest.fn(({ onError, onReset, FallbackComponent }) => {
onError && onError(new Error());
onReset && onReset();
return {
FallbackComponent: ErrorPage,
};
}),
};
});
describe('ReactErrorBoundary', () => {
test('renders ErrorBoundary with ErrorPage as FallbackComponent', () => {
render(<ReactErrorBoundary />);
expect(ErrorBoundary).toHaveBeenCalledWith({
FallbackComponent: expect.any(Function),
onError: expect.any(Function),
onReset: expect.any(Function),
children: undefined,
}, {});
});
test('passes children to ErrorBoundary', () => {
const children = <div>Hello World</div>;
render(<ReactErrorBoundary>{children}</ReactErrorBoundary>);
expect(ErrorBoundary).toHaveBeenCalledWith({
FallbackComponent: expect.any(Function),
onError: expect.any(Function),
onReset: expect.any(Function),
children: <div>Hello World</div>,
}, {});
});
test('logs error message when onError is triggered', () => {
const spy = jest.spyOn(console, 'log').mockImplementation();
const error = new Error("Test error message");
render(<ReactErrorBoundary><div>Error occurred!</div></ReactErrorBoundary>);
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledWith('Error caught!', error);
spy.mockRestore();
});
});
When I run the third test, I get the following error:
ReactErrorBoundary › logs error message when onError is triggered
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
I think it is because I am mocking react-error-boundary but even when I modify that mock it does not work. I would appreciate any help!