I have an app which exposes a script as a command. How do I test this script using jest. More specifically how to execute this script using jest and then apply the corresponding expectations? The script does not export any functions, It just contains a bunch of lines of code which are executed sequentially.
The jest command line runner has a number of useful options. You can run jest --help to view all available options. Many of the options shown below can also be used together to run tests exactly the way you want. Every one of Jest's Configuration options can also be specified through the CLI. Here is a brief overview: Run all tests (default):
Let’s configure the npm test script to run the Jest tests i.e. when the command ‘npm test’ is executed, the script should run all the Jest framework based tests. To do that, update the package.json file and add a script section as shown below.
Now hands on Jest! As with every JavaScript project you'll need an NPM environment (make sure to have Node installed on your system). Create a new folder and initialize the project with: Next up install Jest with: Let's also configure an NPM script for running our tests from the command line.
In this Jest tutorial, we will learn about various Jest features, Jest Matchers, and how to use the Jest framework for JavaScript Unit Testing: Jest is a Javascript Testing framework built by Facebook.
You could wrap your code in a main
function, export it, and only run the function when executing the module from the command line, and then write tests for it. A simplified example could be:
// script.js
const toUpper = text => text.toUpperCase();
module.exports.toUpper = toUpper;
// It calls the function only if executed through the command line
if (require.main === module) {
toUpper(process.argv[2]);
}
And then import the toUpper
function from the test file
// script.test.js
const { toUpper } = require('./script');
test('tranforms params to uppercase', () => {
expect(toUpper('hi')).toBe('HI');
});
See Node: Accessing the main module
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