Home > Software engineering >  Jest Mocking Component Doesn't Mock Function
Jest Mocking Component Doesn't Mock Function

Time:08-02

I am trying to write a test and mock out a component. However, whenever I run my test I get an error:

TypeError: getDistance is not a function

I assume that mocking a component would also remove its function calls.

Test File for TopLevel for what I have now:

   jest.doMock("./NestedComponent", () => () => {
       const MockName = () => {
          return <div />
        };
        return <MockName />;
   });

Component File:

const TopLevel = () => {
   return (
      <>
        <div>
          <NestedComponent />
        </div>
      </>
   )
}

NestedComponent file

const NestedComponent = () => {
   const distance = getDistance();
   return (
      <div>
        {distance}
      </div> 
   )
}
export default NestedComponent

CodePudding user response:

Without a codesandbox, it's quite hard to tell, but I'm going to take a guess its because you are using doMock as opposed to mock.

With doMock, the mock is not hoisted meaning that the import for your top level component, and subsequently, the import for the nested component you are attempting to mock, is loaded into memory before the mock comes into affect -- such is the behaviour of static ESM imports.

If you use mock instead, the mocking will happen before any of the code is loaded into memory because Jest does some (considerably complex and sometimes problematic) hoisting magic such that it executes before the import.

  • Related