Im learning Jest with TypeScript and I'm facing the following type error:
Property 'mockImplementation' does not exist on type '() => Element'.
Code:
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();
});
I have tried casting any
but that doesn't seem to solve it:
Home.mockImplementation((): any => <div>HomePageMock</div>)
Any ideas?
TIA
CodePudding user response:
You can convince Typescript that this is a jest Mock object by using something like const MockedTheClass = TheClass as jest.Mock<TheClass>
.
Example:
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
});
Source: https://klzns.github.io/how-to-use-type-script-and-jest-mocks