Nir Tzezana
Nir Tzezana

Reputation: 2342

Unit testing with Jest without module.exports

I have a script that holds a single const variable which holds all of my logic, kind-of like Moment.js.
I want to test out functions that go out with this script with Jest.

I can't use module.exports since it will not work when I publish my script.
And if I can't use module.exports I can't use require.

But I still want to run unit tests on my script.
I have tried using import with no luck.

Here is my code:

import 'src/library.js';

test('Something', () => {
    expect(library.add(1,2)).toBe(3);
});

And this is my library:

const library = () => {
    return {
        add : (num1,num2) => num1 + num2,
        subtract : (num1,num2) => num1 - num2
    }
}

Upvotes: 8

Views: 3375

Answers (2)

more urgent jest
more urgent jest

Reputation: 362

what about wrapping your exports with:

if (typeof exports !== 'undefined') {
    module.exports = { yourWhatever };
}

Upvotes: 10

Geoffrey Hale
Geoffrey Hale

Reputation: 11438

First Option (Quick & Dirty): Don't import. Just move the code into one file.

Second Option (Best Long Term): Learn how to use (webpack and) babel.

Upvotes: 0

Related Questions