使用 require 问题设置循环依赖

Issue setting circular depedencies using require

循环依赖是在 Jest.js 中模拟父函数内部子函数的一种方式。我看过关于如何使用循环导入的 ES6 示例,但我无法使用 require 将其转换为 ES5 语法。这是我拥有的:

const currentFile = require('./targetFile.js');

const a = () => {
  return currentFile.b();
};

const b = () => {
  return 'from b'
};

module.exports = { a, b }

然后我尝试 运行 测试文件中的上述代码需要将上述代码作为 targetFile:

const targetFile = require("../targetFile.js");

test('a and b', () => {
  console.log(targetFile.a(), `=====targetFile.a()=====`);
});


 FAIL  views/admin/__tests__/targetFile.test.js
  ✕ a and b (12ms)

  ● a and b

    TypeError: currentFile.b is not a function

      26 | 
      27 | const a = () => {
    > 28 |   return currentFile.b();
         |                      ^
      29 | };
      30 | 
      31 | const b = () => {

以上使用 requires(或其他 ES5 浏览器兼容语法)的正确语法是什么?

由于技术原因,module.exports = {} 语法不适用于循环依赖。幸运的是,您可以使用 exports.a = a 语法,并像 const target = require('target');.... target.a();

一样使用它

总的来说,循环导入带来的麻烦多于好处,所以我建议避免使用它们。我也不明白为什么您需要循环导入进行测试,并且您的示例也没有显示。你能 post 更详细地了解你的文件吗?