javascript - JavaScript:模块/要求未定义
问题描述
我想让 Jest 测试我在 Web 应用程序前端使用的一些 JavaScript 代码。据我了解,我需要从我的模块中导出和导入函数,以便我可以在 Jest 中测试它们,并且 Jest(仅)支持开箱即用的 CommonJS 模块语法。结果,我的代码如下所示:
<!-- index.html -->
<!DOCTYPE html>
<html><body><div>Hello World</div>
<script src="./utils.js">
console.log('foo: ' + foo());
</script>
</body></html>
// utils.js
function foo() {return 42;}
module.exports = {foo};
// __test__/utils.test.js
const utils = require('../utils');
describe('utils', () => {
test('foo', () => {expect(utils.foo()).toBe(42);});
});
测试部分有效,但是当我index.html
在浏览器中打开时,我得到
未捕获的 ReferenceError:未定义模块
我的理解是前端不支持 CommonJS 模块语法(根据Client on node: Uncaught ReferenceError: require is not defined)。我应该如何编写我的utils.js
文件并导出以便我可以:
- 对以下组件进行 Jest 测试
utils.js
utils.js
使用浏览器中定义的函数
为了清楚起见,我不想从浏览器运行我的测试。
对于上下文:在我的真实用例中,我使用 Express 和 Node.js 运行应用程序,但这个最小的示例应该能捕捉到潜在的问题。
另外,请参阅此相关问题:未捕获的 ReferenceError: module/require is not defined
解决方案
尝试检查是否module
存在:
// utils.js
function foo() { return 42; }
if(module) module.exports = {foo}; // On node.js, use exports
else if(window) window.foo = foo; // In browser, use window
else console.error('Unknown environment');
在浏览器中:
<!-- index.html -->
<!doctype html>
<html>
<body>
<script src="./utils.js"></script>
<script>
// Use your foo() here!
console.log('foo: ', window.foo());
</script>
</body>
</html>
推荐阅读
- c# - 在 ConfigureServices 方法中访问数据库
- node.js - Nodejs可读流,在expressjs中使用管道无法响应
- intellisense-documentati - javascript中的三点操作被vscode intelisense阻止
- java - 无需任何交易即可将 PayPal Vault 保存在 Braintree 中
- c++ - MinGW-w64 g++ 不生成可执行文件
- neo4j - new Neo4jGraphQL({ typeDefs, driver }) 导致未知指令错误
- c - 我可以确定重新分配更少的内存总能找到足够的内存吗?
- flutter - Flutter 依赖兼容性问题“syncfusion_flutter_pdf”
- java - 如何正确实现 BLE scanCallback 的 ScanFilters?
- ios - 如何设置导航控制器后退按钮的 alpha 值?