Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 888
Nir Tzezana Avatar asked Sep 25 '18 20:09

Nir Tzezana


People also ask

Can Jest be used for unit testing?

Jest JavaScript resting framework with a focus on simplicity. Jest was created by Facebook engineers for its React project. Unit testing is a software testing where individual units (components) of a software are tested. The purpose of unit testing is to validate that each unit of the software performs as designed.

Is Jest enough for testing?

Jest is a JavaScript test runner that lets you access the DOM via jsdom . While jsdom is only an approximation of how the browser works, it is often good enough for testing React components.

Can you use Jest without Node?

Jest uses describe and it and expect without you having to require them. This is okay because if you have a test file called test. spec. js , you'll never execute it directly by issuing the command node test.

Is it possible to write tests in Nodejs without an external library?

If you've ever written tests for a Node. js application, chances are you used an external library. However, you don't need a library to run unit tests in Javascript.


1 Answers

what about wrapping your exports with:

if (typeof exports !== 'undefined') {
    module.exports = { yourWhatever };
}
like image 119
more urgent jest Avatar answered Oct 22 '22 03:10

more urgent jest