8

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
    }
}
Nir Tzezana
  • 2,275
  • 3
  • 33
  • 56

2 Answers2

10

what about wrapping your exports with:

if (typeof exports !== 'undefined') {
    module.exports = { yourWhatever };
}
more urgent jest
  • 362
  • 4
  • 11
  • Great one. It will be helpful when the client does not approve of us using other libraries like Webpack and Babel or for any other reason. Caveat: It looks like a code smell. – Carlos Querioz Nov 06 '21 at 17:01
0

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.

Geoffrey Hale
  • 10,597
  • 5
  • 44
  • 45