JestJS TypeScript:类型上不存在 mockImplementation
JestJS TypeScript: mockImplementation Does not Exist on Type
我正在使用 TypeScript 学习 Jest,我遇到了以下类型错误:
Property 'mockImplementation' does not exist on type '() => Element'.
代码:
test("Should Render HomePage on Default Route", () => {
// Arrange
Home.mockImplementation(() => <div>HomePageMock</div>) // type error here
// Act
render(
<MemoryRouter>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</MemoryRouter>
);
// Assert
const element = screen.getByText("HomePageMock");
expect(element).toBeInTheDocument();
});
我试过转换 any
但这似乎没有解决问题:
Home.mockImplementation((): any => <div>HomePageMock</div>)
有什么想法吗?
TIA
您可以使用 const MockedTheClass = TheClass as jest.Mock<TheClass>
.
之类的东西让 Typescript 相信这是一个开玩笑的 Mock 对象
示例:
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
});
来源:https://klzns.github.io/how-to-use-type-script-and-jest-mocks
我正在使用 TypeScript 学习 Jest,我遇到了以下类型错误:
Property 'mockImplementation' does not exist on type '() => Element'.
代码:
test("Should Render HomePage on Default Route", () => {
// Arrange
Home.mockImplementation(() => <div>HomePageMock</div>) // type error here
// Act
render(
<MemoryRouter>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</MemoryRouter>
);
// Assert
const element = screen.getByText("HomePageMock");
expect(element).toBeInTheDocument();
});
我试过转换 any
但这似乎没有解决问题:
Home.mockImplementation((): any => <div>HomePageMock</div>)
有什么想法吗?
TIA
您可以使用 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
});
来源:https://klzns.github.io/how-to-use-type-script-and-jest-mocks