JavaScript:未定义模块/要求

unt*_*gam 5 javascript commonjs jestjs module.exports

I'd like to have Jest testing for some JavaScript code that I'm using in the frontend of my web app. From what I understand, I need to export and import functions from my module so I can test them in Jest, and Jest (only) supports CommonJS module syntax out of the box. As a result, my code looks as follows:

<!-- index.html -->
<!DOCTYPE html>
<html><body><div>Hello World</div>
<script src="./utils.js">
    console.log('foo: ' + foo());
</script>
</body></html>
Run Code Online (Sandbox Code Playgroud)
// utils.js
function foo() {return 42;}
module.exports = {foo};
Run Code Online (Sandbox Code Playgroud)
// __test__/utils.test.js
const utils = require('../utils');
describe('utils', () => {
    test('foo', () => {expect(utils.foo()).toBe(42);});
});
Run Code Online (Sandbox Code Playgroud)

The testing part works, but when I open index.html in the browser I get

Uncaught ReferenceError: module is not defined

My understanding is that the frontend does not support CommonJS module syntax (according to Client on node: Uncaught ReferenceError: require is not defined ). How should I write my utils.js file and exports such that I can:

  1. have Jest testing for components of utils.js
  2. use functions defined in utils.js in the browser

只是要清楚,我希望从浏览器中运行我的测试。

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

另外,请参阅此相关问题:Uncaught ReferenceError: module/require is not defined

Jav*_*Dev 2

尝试检查是否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');
Run Code Online (Sandbox Code Playgroud)

在浏览器中:

<!-- index.html -->
<!doctype html>
<html>
  <body>
    <script src="./utils.js"></script>
    <script>
      // Use your foo() here!
      console.log('foo: ', window.foo());
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我必须使用 if(typeof module !== 'undefined')` 作为 if 条件,但这很简单并且有效,我将使用它作为短期修复。感觉有点老套,所以考虑改用 Mocha 进行测试 (2认同)