将函数导入 jest.mock 以避免样板代码

Import function into jest.mock to avoid boilerplate code

我认为这一定是一个非常简单的解决方案,但我正在努力寻找解决方案。

我的测试顶部有一个函数:

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

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

所以,我知道 jest.mock 在每个测试 运行 中都被提升到导入语句之上,但是我想减少这个文件中我需要的样板代码,并且举个例子,如果 setWidth 是一个非常大的函数,我想从另一个文件导入它,有什么办法可以做到这一点吗?

如果我将 setWidth 移动到另一个文件并尝试以下操作,由于提升

而失败
import { setWidth } from ./setWidth

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

收到的错误是:

  ● Test suite failed to run
Invalid variable access: setWidth

提前感谢您提供任何可能的解决方案!

jest.mock 被提升到 import 之上,所以这不起作用。但是你可以做的是使用 requireActual

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

看起来您开始对 "testing infrastructure" 有点着迷了 - 尝试考虑是否有更多 "real" 方式(较少的测试基础设施)来测试您的代码。

最可能的方法是将您的测试代码分解成更小的 functions/components。