I am exporting my js file, so I can use import into my unit test file. Here is my js file:
function getComputerChoice() {
//stuff here
}
function playRound(playerSelection, puterSelection) {
//stuff here
}
function game() {
// stuff
}
module.exports = {
getComputerChoice,
playRound,
game,
};
And in my test file, I am importing it this way:
const rockPaperScissors = require('../rockPaperScissors');
test('Verify the case for tie', () => {
expect(rockPaperScissors.playRound('rock', 'rock')).toBe('TIE');
});
test('Verify the case for win', () => {
expect(rockPaperScissors.playRound('rock', 'scissors')).toBe('WIN');
});
test('Verify the case for lose', () => {
expect(rockPaperScissors.playRound('rock', 'paper')).toBe('LOSE');
});
The only way I can get my test file to work, is by exporting in the above format, but when I run the index.html in for this page, I see Uncaught ReferenceError: module is not defined
.
I am exporting my js file, so I can use import into my unit test file. Here is my js file:
function getComputerChoice() {
//stuff here
}
function playRound(playerSelection, puterSelection) {
//stuff here
}
function game() {
// stuff
}
module.exports = {
getComputerChoice,
playRound,
game,
};
And in my test file, I am importing it this way:
const rockPaperScissors = require('../rockPaperScissors');
test('Verify the case for tie', () => {
expect(rockPaperScissors.playRound('rock', 'rock')).toBe('TIE');
});
test('Verify the case for win', () => {
expect(rockPaperScissors.playRound('rock', 'scissors')).toBe('WIN');
});
test('Verify the case for lose', () => {
expect(rockPaperScissors.playRound('rock', 'paper')).toBe('LOSE');
});
The only way I can get my test file to work, is by exporting in the above format, but when I run the index.html in for this page, I see Uncaught ReferenceError: module is not defined
.
- seems like you're trying to run the code in a browser, and the error you're getting is saying that the module is not defined. If this code is intended to be run in a browser, you'll have to package it with Webpack or Browserify first – Abhilash.k.p Commented Jul 22, 2022 at 6:41
- Yes, I'm just running this in my browser console. Is that the problem? – bigeasy Commented Jul 22, 2022 at 6:55
- Yes, you need to pile it to plain javascript to run this in browser console. browser won't understand the module object. – Abhilash.k.p Commented Jul 22, 2022 at 6:59
1 Answer
Reset to default 3require
and module.exports
are part of the CommonJS module system which is Node.js' default module system.
Browsers have no support for CommonJS so if you want to use code written using it you will need to convert it to a format that browsers do support. Typically this is done using a bundler such as Webpack or Parcel.
Browsers do support standard JavaScript modules (so long as you load them with <script type="module">
) which use import
and export
so you could also rewrite your modules to use that.