gpt4 book ai didi

javascript - 使用 require 问题设置循环依赖

转载 作者:行者123 更新时间:2023-11-30 19:31:18 24 4
gpt4 key购买 nike

循环依赖是在 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(); 一样使用它

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

关于javascript - 使用 require 问题设置循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56413738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com