I am mocking a React component using Jest, but TypeScript is not recognizing the mocked methods and giving a TS2339 error.
Here's my test:
jest.mock('./features/News/News');
describe('<App />', () => {
it('should render the News page on default route', () => {
// The following line is giving an error:
// TS2339: Property 'mockImplementation' does not exist on type '() => Element'.
News.mockImplementation(() => <div>NewsPageMock</div>);
render(
<MemoryRouter>
<App />
</MemoryRouter>
);
expect(screen.getByText('NewsPageMock')).toBeInTheDocument();
});
});
@ts-ignore
to ignore the error, but that's a hack.mocked()
function to workaround this. However this is a create-react-app which uses babel, so don't want to introduce ts-jest.Any other way to make TypeScript happy?
I came up with a better hack than @ts-ignore
. Here it is:
(News as jest.Mock).mockImplementation(() => <div>NewsPageMock</div>);
This is good enough for me, but happy to consider other answers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.