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
}
}
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.
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.
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.
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.
what about wrapping your exports with:
if (typeof exports !== 'undefined') {
module.exports = { yourWhatever };
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With