3

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

1

1 Answer 1

12

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

2
  • 2
    Thanks for your help! Typescript didn't like <TheClass> but once removed then it seems to work with no type errors!
    – yush
    Feb 15, 2022 at 12:11
  • In my case I have to either leave out the type or use <JSX.Element>
    – yush
    Feb 15, 2022 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.