我想让 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
文件并导出以便我可以:
- 对以下组件进行 Jest 测试
utils.js
utils.js
使用浏览器中定义的函数
为了清楚起见,我不想从浏览器运行我的测试。
对于上下文:在我的真实用例中,我使用 Express 和 Node.js 运行应用程序,但这个最小的示例应该能捕捉到潜在的问题。
另外,请参阅此相关问题:未捕获的 ReferenceError: module/require is not defined