【问题标题】:TypeScript error TS2339 when React component mocked with Jest使用 Jest 模拟 React 组件时出现 TypeScript 错误 TS2339
【发布时间】: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


    【解决方案1】:

    我想出了一个比@ts-ignore 更好的技巧。这里是:

    (News as jest.Mock).mockImplementation(() => <div>NewsPageMock</div>);
    

    这对我来说已经足够了,但很高兴考虑其他答案。

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 1970-01-01
      • 2021-01-03
      • 2021-12-10
      • 2018-11-09
      • 2022-08-09
      • 1970-01-01
      • 2021-04-21
      • 2019-09-11
      相关资源
      最近更新 更多