Tutorial to Add Jest testing to Node app

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

While Jest is often used with React, it can also be used on Node apps (without React) as well. It is just a Javascript testing framework.

In this tutorial, we will add Jest to a “simple” Node app.

Start off by creating a simple Node app…

mkdir simple
cd simple
npm init

Then install Jest as a dev-dependency…

npm install --save-dev jest

This add Jest as a dev-dependence in package.json …

While we are in package.json, update the “scripts” section to have the “npm test” script run “jest src”. See highlight in above screenshot.

The command “jest src” will tell Jest to run all test in the folder “src” and its sub-folder. It will know which files are the test files to run, because you are going to name all your Jest test files with extension *.spec.js or *.test.js

We run on the “src” folder because that is where we are going to put our “source code” right now. Create the folder “src” and the file “greet.js” with the following code to be tested…

Now create an src/index.js file as the starting point of our simple Node app which will “require” and use this “greetByName” function …

See in line 2 we “require” our greet.js file and in line 10 we use the function greetByName, passing in the name “John”.

Update the package.json to indicate that our Node app starting point is src/index.js …

And let’s also an our npm start script …

We can now start our Node app with “npm start” in the terminal, instead of typing “node src/index.js”

Launching browser to “http://localhost:3000” we get “Hello John” indicating everything working as expected.

Writing First Jest Test Case

Now let write our test case.

Create our test file greet.test.js in “src” folder with content …

See how it “requires” the file to be tested and uses the function.

Run the Jest tests with “npm run test” in the terminal…

This is the most basic test. But often you will have more than one test. You will want to group them inside a “describe” test suite. And change your test case to “it” like this …

If you run “npm test”, it will say two test pass, but the last test fails with this error …

By writing test cases, we found that we forgot to write code in our app that handles the case when no name is passed.

We fix our app code by updating our “greet” function…

beforeEach

If you want some code to run before each “it” test, you can add beforeEach hook like this…

Similarly, there is also an “afterEach”.

There is also “beforeAll”, which is run once for each “describe” block and prior to running any “beforeEach”.

Similarly for “afterAll”. These concepts are part of Jasmine, since Jest is based on Jasmine.


Related Posts

Tags

Share This