JavaScript:模块/要求未定义

标签 javascript jestjs commonjs module.exports

我想让 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在我得到的浏览器中

Uncaught ReferenceError: module is not defined


我的理解是前端不支持 CommonJS 模块语法(根据 Client on node: Uncaught ReferenceError: require is not defined )。
我应该如何写我的utils.js文件并导出,以便我可以:
  • utils.js 的组件进行 Jest 测试
  • 使用 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>
    

    关于JavaScript:模块/要求未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63752210/

    相关文章:

    javascript - 如何解决 Require.js 中的循环依赖?

    javascript - 不导出时 typescript "exports not defined"错误

    javascript - 使用 Browserify/CommonJS 的单例模式

    javascript - 如何在传单中仅显示一个县?或者重建这张 map ?

    javascript - 不能给边框空间并在上面打印一个字

    javascript - 如何一起使用$.hoverIntent和setTimeout?

    javascript - JS 一直有效,直到我将它带入基础框架

    unit-testing - axios 捕获错误请求失败,状态码为 404

    javascript - elementHandle.$x(expression) 似乎没有相对于给定的 elementHandle 运行

    node.js - 用 Jest 测试 GraphQL 解析器