Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jest to test a command line tool

Tags:

jestjs

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.

like image 205
Nahush Farkande Avatar asked Nov 16 '16 09:11

Nahush Farkande


People also ask

How do I use the jest command line runner?

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):

How to configure NPM test script to run jest tests?

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.

How do I get Started with jest?

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.

What is jest testing?

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.


1 Answers

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

like image 67
Pablo Navarro Avatar answered Oct 22 '22 03:10

Pablo Navarro