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:
utils.jsutils.js in the browser只是要清楚,我不希望从浏览器中运行我的测试。
对于上下文:在我的实际用例中,我使用 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');
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)
| 归档时间: |
|
| 查看次数: |
1742 次 |
| 最近记录: |