![](/img/trans.png)
[英]React + TypeScript: Passing React Component as Props, rendering with props [Error: TS2339]
[英]TypeScript error TS2339 when React component mocked with Jest
我是 mocking 一個使用 Jest 的 React 組件,但 TypeScript 無法識別模擬方法並給出 TS2339 錯誤。
這是我的測試:
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
來忽略錯誤,但這是一個 hack。mocked()
function 來解決這個問題。 然而這是一個使用 babel 的 create-react-app,所以不想引入 ts-jest。還有其他方法可以讓 TypeScript 開心嗎?
我想出了一個比@ts-ignore
更好的技巧。 這里是:
(News as jest.Mock).mockImplementation(() => <div>NewsPageMock</div>);
這對我來說已經足夠了,但很高興考慮其他答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.