gpt4 book ai didi

typescript - JestJS TypeScript : mockImplementation Does not Exist on Type

转载 作者:行者123 更新时间:2023-12-05 01:05:04 26 4
gpt4 key购买 nike

我正在使用 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 相信这是一个 Jest 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 - JestJS TypeScript : mockImplementation Does not Exist on Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71119683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com