Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JestJS TypeScript: mockImplementation Does not Exist on Type

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

like image 617
yush Avatar asked Jul 14 '26 00:07

yush


1 Answers

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

like image 105
rudolfbyker Avatar answered Jul 20 '26 08:07

rudolfbyker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!