[英]TypeScript error TS2339 when React component mocked with Jest
I am mocking a React component using Jest, but TypeScript is not recognizing the mocked methods and giving a TS2339 error.我是 mocking 一个使用 Jest 的 React 组件,但 TypeScript 无法识别模拟方法并给出 TS2339 错误。
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.@ts-ignore
来忽略错误,但这是一个 hack。mocked()
function to workaround this.mocked()
function 来解决这个问题。 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?还有其他方法可以让 TypeScript 开心吗?
I came up with a better hack than @ts-ignore
.我想出了一个比
@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.这对我来说已经足够了,但很高兴考虑其他答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.