首页 > 解决方案 > 使用 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 浏览器兼容语法)的正确语法是什么?

标签: javascriptecmascript-5

解决方案


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

总的来说,循环导入带来的麻烦多于好处,所以我建议避免使用它们。我也看不出为什么需要循环导入进行测试,而且您的示例也没有显示。你能发布更多关于你的文件的细节吗?


推荐阅读