简体   繁体   中英

Import function into jest.mock to avoid boilerplate code

I assume this must be a pretty straightforward solution, but I am struggling to find a solution.

I have a function at the top of my tests:

jest.mock('../someFile', () => {
  const setWidth = () => {
// lots of complex logic
};

  return {
  width: jest
          .fn()
          .mockImplementation(element => {
    setWidth(element);
    };
   };
  };
 };

So, I understand that jest.mock is hoisted above the import statements in every test run, but say I would like to cut down on the boiler plate code I need in this file and as an example if setWidth was a really big function and I want to import it from another file, is there any way I could do this?

If I move setWidth to another file and try the following it fails due to the hoisting

import { setWidth } from ./setWidth

jest.mock('../someFile', () => {
  return {
  width: jest
          .fn()
          .mockImplementation(element => {
    setWidth(element);
   };
  };
 };
};

The error received is:

  ● Test suite failed to run
Invalid variable access: setWidth

Thanks in advance for any possible solutions!

jest.mock gets hoisted above the import, so that won't work. But what you can do is use requireActual

jest.mock('../someFile', () => {
  const { setWidth } = jest.requireActual('./setWidth');
  return {
  width: jest
          .fn()
          .mockImplementation(element => {
    setWidth(element);
   };
  };
 };
};

Looks like you're starting to go a bit crazy with "testing infrastructure" though - try to consider if there's a more "real" way (less testing infrastructure) you can test your code.

The most likely way to do this is to break the code your testing down into smaller functions/components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM