【发布时间】:2021-05-26 07:21:17
【问题描述】:
我正在使用 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。 - 我知道 ts-jest 提供了一个
mocked()函数来解决这个问题。不过这是一个使用 babel 的 create-react-app,所以不想引入 ts-jest。
还有其他让 TypeScript 开心的方法吗?
【问题讨论】:
标签: reactjs typescript jestjs