JavaScript:未定义模块/需求

问题描述

我想对Web应用程序前端中使用的一些JavaScript代码进行Jest测试。 据我了解,我需要从模块中导出和导入函数,以便可以在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. utils.js的组件进行了Jest测试
  2. 在浏览器中使用utils.js中定义的功能

请明确一点,我不是要从浏览器运行测试。

对于上下文:在我的实际用例中,我使用Express和Node.js运行应用程序,但是这个最小的示例应该可以解决潜在的问题。

另外,请参见以下相关问题:Uncaught 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>
,

我在从我的主 js 文件导出时遇到了类似的 jest 错误

以下对我来说效果很好

if (typeof module !== 'undefined') module.exports = { foo };

PS:我已经放弃了 JS 代码的模块化,因为 js 模块会抛出 cors 错误,因为我的 (html,js) 代码运行在远程到 Windows 应用程序的浏览器进程中,更重要的是 html、js 代码从磁盘加载而不是服务器。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...