I'm relatively new to NodeJS and the concept of unit testing.
Currently, I am using Jest
, although the issue seems to persist with Mocha
, Ava
, or any other test framework. It appears that my problem revolves around the usage of export
/import
.
In one file named learning.js
, I have defined some functions:
// learning.js
function sum(a, b) {
return a + b
}
const multiply = (a, b) => a * b
module.exports = { sum: sum, multiply: multiply }
Additionally, there is another file called some.test.js
:
// some.test.js
const { sum, multiply } = require('./learning')
// const { sum, multiply } = require('./another')
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3)
})
test('multiplies 2 x 2 to equal 4', () => {
expect(multiply(2, 2)).toBe(4)
})
At this point, everything runs smoothly, and all tests pass successfully.
However, there is a third file named another.js
structured in the following way (utilizing express
):
router.get('/another', async function(req, res) {
// TESTING
function sum(a, b) {
return a + b
}
const multiply = (a, b) => a * b
// PERFORM OTHER OPERATIONS...
res.status(200).send('ok')
})
module.exports = { sum: sum, multiply: multiply }
// module.exports = router
When attempting to run the same tests from some.test.js
(by simply modifying the require
statement to point to another.js
), the tests fail with the message:
TypeError multiply is not a function
.
I have experimented with moving the export
statements elsewhere, as well as trying out different naming conventions using dot notation
, yet I still cannot resolve the issue.
Any insights or suggestions would be greatly appreciated. Thank you!