JestJS TypeScript:类型上不存在模拟实现

yus*_*ush 5 typescript jestjs

我正在使用 TypeScript 学习 Jest,但遇到以下类型错误:

Property 'mockImplementation' does not exist on type '() => Element'.
Run Code Online (Sandbox Code Playgroud)

代码:

Property 'mockImplementation' does not exist on type '() => Element'.
Run Code Online (Sandbox Code Playgroud)

我尝试过强制转换any,但这似乎无法解决问题:

Home.mockImplementation((): any => <div>HomePageMock</div>)
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

TIA

rud*_*ker 16

您可以使用类似const MockedTheClass = TheClass as jest.Mock<TheClass>.

例子:

import { TheClass } from "the-module";
jest.mock("the-module");
const MockedTheClass = TheClass as jest.Mock<TheClass>;

describe("something", () => {
  beforeEach(() => {
    // No error here (except if your implementation does not match the spec of `TheClass`)
    MockedTheClass.mockImplementation(() => {
      // ... implementation
    });
  });

  // ... tests
});
Run Code Online (Sandbox Code Playgroud)

来源:https ://klzns.github.io/how-to-use-type-script-and-jest-mocks

  • 感谢您的帮助!Typescript 不喜欢``&lt;TheClass&gt;```,但一旦删除,它似乎就可以正常工作,没有类型错误! (2认同)