Donotalo
Donotalo

Reputation: 13025

JS module exports aren't working with Jest

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:

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

Answers (2)

Eldynn
Eldynn

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

Andre
Andre

Reputation: 458

if you do exports.sum = sum;

You need to import it like: const {sum} = require('../controllers/a');

Upvotes: 2

Related Questions