首页 > 解决方案 > 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文件并导出以便我可以:

  1. 对以下组件进行 Jest 测试utils.js
  2. utils.js使用浏览器中定义的函数

为了清楚起见,我不想从浏览器运行我的测试。

对于上下文:在我的真实用例中,我使用 Express 和 Node.js 运行应用程序,但这个最小的示例应该能捕捉到潜在的问题。

另外,请参阅此相关问题:未捕获的 ReferenceError: module/require is not defined

标签: javascriptjestjscommonjsmodule.exports

解决方案


尝试检查是否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>

推荐阅读