我想让 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/