Reputation: 13025
I'm trying to setup Jest
on a Node.js
environment. Following is a function defined in a file named controllers/a.js
:
function sum(a, b) {
return a + b;
}
module.exports = sum;
This is accessed from the tests.js
file:
const sum = require('../controllers/a');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
This works fine:
PASS tests/tests.js
√ adds 1 + 2 to equal 3 (5 ms)
However, if I modify a.js
as follows:
function sum(a, b) {
return a + b;
}
exports.sum = sum;
then I get TypeError
:
FAIL tests/tests.js
× adds 1 + 2 to equal 3 (3 ms)
● adds 1 + 2 to equal 3
TypeError: sum is not a function
2 |
3 | test('adds 1 + 2 to equal 3', () => {
> 4 | expect(sum(1, 2)).toBe(3);
| ^
5 | });
Tried the following ways to export, all failed with the TypeError
above:
module.exports.sum = sum;
module.exports = { sum: sum };
exports = sum;
exports = { sum: sum };
I need to export multiple functions for testing in Jest
. How can I do that if Jest
doesn't recognize module.exports
as expected?
Upvotes: 0
Views: 2104
Reputation: 183
Have you tried:
function sum() { ... }
exports.sum = sum;
and in your test:
const { sum } = require('../controllers/a');
Because when you import your file in your test you need to look inside the object returned by require() to find the correct function (here sum).
Upvotes: 3
Reputation: 458
if you do exports.sum = sum;
You need to import it like: const {sum} = require('../controllers/a');
Upvotes: 2