Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mock inner function of a functional component

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading