javascript - 使用 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();
总的来说,循环导入带来的麻烦多于好处,所以我建议避免使用它们。我也看不出为什么需要循环导入进行测试,而且您的示例也没有显示。你能发布更多关于你的文件的细节吗?
推荐阅读
- r - 使用 mutate 和 case_when 遍历列
- pjsip - PJSIP 客户端不确认邀请响应
- angular - Angular:ngIf 不适用于 object.property
- c++ - 在 C++ 上读取外部文件
- sql-server - SSMS 中 AD 用户的 Azure SQL 授予访问权限
- java - Scala 编译器如何决定它需要提供匹配错误?
- botframework - 如何在没有 Magic Code 的情况下验证 Bot
- angular - async await 在多个顺序调用中未按预期执行 | 角打字稿
- python - TypeError:不可散列的类型:谷歌云存储初始化中的“列表”
- django - 如何使用 Django 表单填充 FOREIGN KEY