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>
// 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);});
});
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.js
utils.js
in the browserJust to be clear, I do not want to run my tests from the browser.
For context: in my real use-case I run the app using Express and Node.js but this minimal example should capture the underlying problem.
Also, see this related question: Uncaught ReferenceError: module/require is not defined
This usually happens because your JavaScript environment doesn't understand how to handle the call to require() function you defined in your code. Here are some known causes for this error: Using require() in a browser without RequireJS. Using require() in Node.
1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
How can you use a RequireJS installed through Node in the browser? You can just install it with npm install requirejs , and then you have your HTML file have a script element that points to node_modules/requirejs/require. js . Exactly as you show in your code snippet.
Try checking if module
exists:
// 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');
And in browser:
<!-- index.html -->
<!doctype html>
<html>
<body>
<script src="./utils.js"></script>
<script>
// Use your foo() here!
console.log('foo: ', window.foo());
</script>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With