Home > Enterprise >  Mock inner function of a functional component
Mock inner function of a functional component

Time:07-15

My functional component has a few functions to handle the events from html elements and they have some instructions incompatible with Jest (without adding new libs).

Is it possible to mock these inner functions (that are not exported)?

Here's an example:

Component.js

export default function MyComponent() {

  const setTouchPosition = e => {
    const canvas = document.getElementById('canvas');

    const rect = canvas.getBoundingClientRect();
    // .. a few lines omitted for readability
  };

  const draw = e => {
    const canvas = document.getElementById('canvas');
    const context = canvas.getContext('2d');
    // .. a few lines omitted for readability
  };


  // a few more lines
}

CodePudding user response:

You can not mock inner functions, so the right thing to do here would probably be to refactor such that it is more easily testable.

For example, you could break out an inner component which consumes a custom draw rather than defines one, then the outer component would pass down your concrete current draw implementation.

Then you can test the inner component with a passed in mock.

  • Related