Introduction To Testing With Jest

Introduction To Testing With Jest

Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

Why should I write tests?

As software developers, it is our prime responsibility to ensure that we ship apps that are of high quality. Now, how do you know if your app passes the quality test? Well, writing tests to validate the app if one of the fundamental tasks that we need to do as software developers.

Often times, we tend to skip writing tests for our code. And we may have plenty of reasons like meeting deadlines, client doesn’t care about tests, and so on. I believe, writing tests needs to be a part of our everyday job, and we should integrate it within the process.

Alright, enough said about the importance of testing.

If you are developing in JavaScript, one of the most popular and easy to use testing frameworks out there today is Jest.

What is Jest?

**Jest **is a JavaScript testing framework that is widely popular today. It works with all modern JavaScript frameworks like React, Angular, Vue, Node and so on.

If you are someone who hates writing tests, Jest will change your opinion. It is super easy to use and developers love writing tests with Jest.

Tell me more, what is cool about Jest?

No configuration

Remember how long it takes to set-up a testing framework and integrate it within your app. Well, Jest makes things a lot easier and comes with no configuration at all. It comes out of the box on most modern JavaScript frameworks and requires no setup time. Hence, saving you tons of developer time. I use Jest with my React and React Native applications with zero configuration.

Simple Mocking

Jest makes writing mock functions quite simple. It uses custom resolver for imports in your tests, hence making it easy to mock any object that is outside of your test’s scope.


Jest uses snapshots that can make your test keep track of large objects in an organized manner. Snapshots live either alongside your tests, or are embedded inline. This is useful, if you have a huge object stored in the redux store, and want to validate it’s data.

Tests run in Parallel

This is one of the distinguishing feature of Jest, making it suitable for fast paced development. The tests run parallely, in isolation. Since they have their own processes, it maximizes the performance.


Since tests run in parallel, Jest is a fast option for testing. It also runs previously failed tests first, and re-organizes test runs based on how long test files take.

Great Documentation

Jest APIs are documented clearly and are easy to use. You can browse through the Jest APIs to get an idea on how to get started.

If you are interested to learn more about Jest, the talk below from the core team will provide a lot of insights.

Code Coverage

Jest can generate code coverage by simply using the *–coverage *command. No additional setup is needed to generate the coverage report. This can be used to validate your test cases, and predict how many more test cases are needed to achieve better coverage.

Snapshot Testing with Jest

Snapshot testing ensures that your UI does not change in an unexpected manner. The idea is simple. An initial snapshot of UI component is taken, and it is compared to it’s reference snapshot file stored in the test. The test will fail, if the two snapshots don’t match. This will indicate to us that either, the change is unexpected, or the reference snapshot needs to be updated to the latest version of the UI component.

These types of testing are really common while testing mobile applications.

Jest supports snapshot testing your React/React Native components. You may think, it could be a hassle to constantly update the reference snapshots as your UI changes. Jest has this process simplified for you. You would just need to run one command to update the snapshots and the new reference snapshot replaces the old one.

Here is more information from the official blog, on snapshot testing using Jest.

Moving to Jest from an existing codebase

Not everyone is starting a new project all the time. In reality, if you are on an existing codebase with another testing framework and would like to migrate to Jest, it is quite simple.

  • If you are on Jasmine or Mocha, Jest is compatible with these frameworks and the migration is simple.
  • For other frameworks, you can use the codemods to transform your tests automatically.

Migrating existing tests with jest-codemods

Install the third party plugin, jest-codemods. It can be used to handle all the work to migrate these tests.

yarn global add jest-codemods

To transform your existing tests, navigate to the project containing the tests and run:


Who is using Jest?

Jest is used today by many fortune 500 companies to test their products.

It was originally developed by Facebook and has been open sourced for the community to use and contribute to.

Facebook, Twitter, Airbnb, Instagram, Spotify, and many more big players and small startups are all using this framework to test their products that are written in JavaScript.

The state of JavaScript 2018 survey, shows that Jest is the most popular and widely used testing framework for JavaScript. And about 39.6% of the developers have used it and would use it again.

Jest is a solid testing framework and I highly recommend that you give it a shot.

If you liked this article, do share and spread the word.

Understanding Test-Driven Development with Javascript

Understanding Test-Driven Development with Javascript

In this Javascript tutorial takes you through the development of a simple feature in a test driven way. The basic ideas of TDD (Test-Driven Development) are shown, with explanations of why they might be useful.

In this talk Roy Osherove takes you through the development of a simple feature in a test driven way. The basic ideas of TDD are shown, with explanations of why they might be useful. We'll also do some refactoring for the tests and the production code. This talk is based on the upcoming book "The Art of Unit Testing in Javascript" by Roy Osherove.

Testing your JavaScript Code — TDD

Testing your JavaScript Code — TDD

In this article, I will be making use of the Jest testing framework. There are many other frameworks for testing but my current favourite is Jest and I will be using it in this article.

In this article, I will be making use of the Jest testing framework. There are many other frameworks for testing but my current favourite is Jest and I will be using it in this article.

First things first, **what is testing? **Testing (i.e software testing) is an investigation conducted to provide stakeholders with information about the quality of the software product or service under test.

That might have sounded like a lot, let me break it down. Software testing involves the process of checking your code either manually or automatically (well semi-automatically) to make sure the code functions as needed.

The test we will be referring to in this article is the automated test, the tests you want to create to help you find all (or as many as possible) edge cases in your code. I will talk more on the automated tests soon, but first let’s talk about why we test codes.

Types of Test

  • **Unit testing — **is the level of testing that checks individual units (components) of our code in isolation from others, purpose is to ensure each unit of the code functions as designed.
  • **Integration testing — **is the level of testing that combines units as a group and tests how they work together, purpose is to expose the faults that might exist in the interaction individual units.
  • **End-to-End testing — **is the level of testing that checks the flow of a system from beginning to end as a single application and that it behaves as expected, purpose is to identify system errors and strengths and to ensure that the data on the system is secure across all levels of the system.

Why we should test our code

Main reason for testing your code is to have a very stable code, you want your code to do exactly what you want it to do, and you do not want to have to do this test manually, by checking each part. What you do is called an automated test, you use testing frameworks like **Jest. **You write a test suite expecting your code (function) to work in a certain way or return a particular value, if your code does pass this, you know you need more edge cases in your test, except you have enough and have covered it all, but when your test fails, you go back to your code / functionality, you refactor the code and test again — this process is called regression testing.

The popular saying in testing is that your test is meant to fail the first time you run the test.

TDD — Test Driven Development

This is the process of developing a product (software), that relies on repetitions of test and develop cycle, the automated test is meant to come first and fail first time it is run, then you write the function for the test.

The following sequence of steps is generally followed:

  • Add a test
  • Run all tests and see if the new one fails (if there are old tests)
  • Write some code
  • Run tests
  • Refactor code
  • Repeat

The way the Testing framework (in our case — jest) knows the file that it should read the tests from is by checking for any file with the .test.jsor .spec.js extension. I must warn you, TDD requires much more consideration and time than ‘regular’ programming.

Let’s setup

To be able to perform all tests below or even write your own tests, you need to setup your environment for that.

// In your terminal do the following
$ npm init

$ npm install --save-dev jest
// Then in your package.json file
// change the value of test in scripts to jest

  "scripts": {
    "test": "jest"

Enough talk, let’s get our hands dirty — not literally. We will write test for a mini project I created earlier to explain OOP, I already did the testing while building the mini project, I will simply be walking you through what testing is about and how you can perform various tests, then I will show you what I did while testing an earlier created project.

The first thing I did was check that when I create an instance of a Constructor function, it does work. That way I am sure that my constructor is created properly and then I can continue my work from that point.

Then I wrote my constructor function, and keep refactoring it, until it passed my above test.

Let us take a small detour, I will do us a small test and sum function here, so you can see the entire process. First thing we will do is to write a test we think should work for a sum function, which should be something like 2+3 = 5.

So first thing as best practise is to write the test first;

const sum = require('./sum') // assuming name of file will be sum 
                            // and they are in the same directory
test(‘Add 1 and 2 to give 3’, () => {

This will fail the first time because we are yet to write our sum function, then we will write the sum function to make sure we pass this test

function sum(a, b) { return a + b }
module.exports = sum; // so we can import it in the Jest file

This is straightforward and as we can see this will work if we test in our console or even terminal (maybe using node). Now we need to consider edge cases, for instance there is this one you may or may not know,

0.1 + 0.2 = 0.3 // wrong
0.1 + 0.2 = 0.30000000000000004 // correct and this is not only in JavaScript

So how to we test for this edge case, we can go ahead using other matchers to resolve that kind of issue, we can also check to be sure it returns a value (crooked way to go). For this, we will check to make sure it returns a value like 0.300…4.

test(‘Add 0.1 and 0.2 to be close to 0.3’, () => {
    expect(sum(0.1, 0.2)).toBeCloseTo(0.3);

Reason I chose to use **toBeCloseTo **as the matcher (method) for this is because when dealing with decimal values, there are possibilities for more values after the decimal point, depending on what computation is performed on the values, so instead of looking for the exact, I am making sure it is somewhere in that range.

Now you can see how we went from a test, wrote the function to pass the test, expanded our edge case, wrote a test for it and then we will still pass with our function. You can now go ahead to make sure the parameters are always numbers, also test for negative values.

Find below a test suite, the sum function we have above will fail some of the test, you will need to refactor it to pass all the tests.

// this is to connect the sum function with the test file, so Jest knows where the functions are.
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);

test('add -1 to 3 to equal 2', () => {
  expect(sum(-1, 3)).toBe(2);

test('add a string and a Number to equal NaN', () => {
  expect(sum('tolu', 3)).toBe('NaN');

test('adds two strings to equal NaN', () => {
  expect(sum('decagon', 'institute')).toBe('NaN');

test('add two negative numbers -4 and -9 to equal -13', () => {
  expect(sum(-4, -9)).toBe(-13);

test('enter undefined values to output - enter parameters', () => {
  expect(sum()).toBe('You have not entered any paramter')

test('adds numbers in string \'23\' to \'3\' to equal 26', () => {
  expect(sum('23', '3')).toBe(26);

test('Insert NaN as the only argument to equal NaN', () => {

test('Adding special characters like ! and ( to equal NaN', () => {
  expect(sum('!', '*')).toBe('NaN');

test('Adding 2 Decimal numbers - 0.1 and 0.2 to be close to 0.3', () => {
  expect(sum(0.1, 0.2)).toBeCloseTo(0.3);

test('Adding 2 values 0.915 and 0.11 to equal 1.025', () => {
  expect(sum(0.915, 0.11)).toBeCloseTo(1.025);

Before we go deep, let me introduce you to Jest expect Api

The Jest expect Api has a number of matchers you can use, It looks like Jest already accounted for all the things possible to be tested, you can test for truthiness, numbers, objects, arrays containing certain values, and much more. When you’re writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that lets’ you validate different things. We obviously can’t talk about all the matchers or methods possible, we will however talk about .toBe() , .toMatch() , and .toEqual() . To learn more about expectvisit the Jest expect Api documentation page.


.toBe() is used to compare primitive values, It calls to compare values, which is better for testing than === , according to the Jest documentation. You should not use .toBe() with floating point values, like in the case of 0.1 + 0.2 above, it does not resolve to 0.3 , making .toBe()inappropriate for the test, but .toBeCloseTo() is the right method to use for floating-point numbers.

test(‘Add 1 and 2 to give 3’, () => {


.toMatch() is used to compare a string against a regular expression (regex) or against another string. For example, you might not know what a function returns but you know it should have a particular text in it, you can create a regex to test to be sure it is the correct thing that it returns; let us use returnString() as our function, it returns 'I am learning testing with you, yes you!' , remember we do not know it returns the above, we are going to then write a test to check using regex and also another test for when we are sure of what we want it to return, we can also use just a part of the expected string.

test(‘A statement on learning’, () => {
    expect(returnString()).toMatch(/testing/); // using regex
    expect(returnString()).toMatch('I am learning testing with you, yes you') // using the exact string you want returned
    expect(returnString()).toMatch('I am learning ') // using just a part of the string


.toEqual() is used to compare that two objects are same to the detail (checking all properties of the Object). It also calls to compare values, which is better for testing than === (strict equality), according to the Jest documentation.

const obj1 = {
    isArticle: true,
    title: 'Testing your JavaScript Code — TDD'
const obj2 = {
    isArticle: true,
    title: 'Testing your JavaScript'
const obj3 = {
    isArticle: true,
    title: 'Testing your JavaScript Code — TDD'
test(‘Checking two objects to make sure they are qual’, () => {
    expect(obj1).toEqual(obj2); // wrong
    expect(obj1).toEqual(obj3); // correct

You can run the above to be sure. You should also check out the Jest Documentation to learn more about Jest and testing in general.

With our not so little detour, I guess you should have familiarised yourself with Jest, it’s expect Api and what is happening in our test file. Now back to the subject matter, we will add some more test for our OOP functions, I will explain some of the tests here and show you what your output should look like when you are yet to pass your tests and when you do pass all. If you want a peek at the full test suite and the functions, you should clone the repository.

So let’s add the test cases;

// Import the necessary files for the test to work.

// ...

test('Creating a student Record', function() {
  var jon = new User('Jon Snow', '[email protected]', 'iknownothing', 'teacher');
  var arya = new User('Arya Stark', '[email protected]', 'agirlhasnoface');
  expect(jon.createRecord('4.3', 'Very brilliant chap', '0032')).toBe('Student Record Successfully added');
  expect(arya.createRecord('3.0', 'Decent Attempt', '0012')).toBe('You do not have permission to do this');

test('Reading a record by Id', function() {
  var cersei = new User('Cersei Lannister', '[email protected]', 'neckkk', 'admin');
  var sansa = new User('Sansa Stark', '[email protected]', 'ithoughtyouwerethewisest');
  expect(cersei.readById(1)).toEqual(expect.objectContaining({grade : '4.3'}));
  expect(sansa.readById(1)).toMatch('You do not have per');

// ...

test('Editing a Student Record', function() {
  var jon = new User('Jon Snow', '[email protected]', 'iknownothing', 'teacher');
  var petyr = new User('Petyr Baelish', '[email protected]', 'iamlittlefinger', 'parent');
  expect(jon.updateStudentRecord(1, '4.5', 'This young chap keeps breaking his own records')).toMatch('Student Record');
  expect(petyr.updateStudentRecord(1, '4.34', 'Nothing lasts, so keep working hard')).toBe('You do not have permission to do this');

test('Deleting a student Record', function() {
  var jon = new User('Jon Snow', '[email protected]', 'iknownothing', 'teacher');
  var cersei = new User('Cersei Lannister', '[email protected]', 'neckkk', 'admin');
  expect(cersei.createRecord('4.25', 'His head is really on his neckkk', '0117')).toBe('Student Record Successfully added');
  expect(cersei.deletedAStudentRecord(2)).toBe('Student Record Deleted');
  expect(jon.deletedAStudentRecord(1)).toMatch('You do not have ');

The first test case above is for the creation of a student record, we first instantiate the user we want to use to create the record from the User Constructor, then we call the .createRecord method on the user — jon.createRecord('4.3', 'Very brilliant chap', ‘0032’) , and then we use the .toBe() matcher, to check if it returns the exact return value. Notice me checking for when a student (user without permission) is trying to do same function and what it returns.

The second test checks for when an Admin reads a student record by its’ Id. As you can see we have use the .toEqual() and .toMatch() methods in this test. Like the other cases, we create a user to test, we then perform the .readByIdmethod — cersei.readById(1) , we then use the .toEqual() matcher and then you can see the expect.objectContaining() — this part now expects a return value that will be an object and should contain what is stated in the parenthesis — trick here is to add the object literal {} in the parenthesis before the key: 'value' pair, this will help resolve it into an object. And then on the next line we are testing for when a user without permission attempts to carry out the function and then we use the .toMatch() method and then we test against a part of the full string.


This is one part of jest I love so much, it helps you know how much of your code you have covered. You are able to know the parts of your code you are yet to test, and you know you have done a good job when you hit full 100 on all parts of your code.

As you can see, I have not hit 100 on all, with a few edge cases tested I am able to complete this coverage to hit a full 100. You should strive for 100 but do not kill yourself in the process (i.e. do not wast valuable time), there are more things to do than trying to hit 100 but before you stop trying to kill yourself make sure you hit a 92% at the least.

To get coverage in your tests add --coverage to your scripts in package.json .

  "scripts": {
    "test": "jest --coverage"

Below is my complete Suite — with 100% coverage.

beautiful isn’t it 😍

Running Tests

Running a test suite or just one test or any test at all is really simple and straightforward, all you need is npm run test . When you enter this in your terminal and tap on your enter button (while you are in your project folder), jest will find the test files and run the test.

Introduction to Automating Testing in JavaScript with Jest

Introduction to Automating Testing in JavaScript with Jest

In this Jest tutorial for beginners: Learn the fundamentals of automating testing with Jest in your JavaScript projects. In this tutorial, we will be talking about testing our code in JavaScript with Jest. We will then proceed with the explanation through Q&A’s as I hope this approach would be better than writing a long story. Let’s dive in without wasting much time.

In this article, we will be talking about testing our code in JavaScript. We will then proceed with the explanation through Q&A’s as I hope this approach would be better than writing a long story. Let’s dive in without wasting much time.

What are tests?

It’s as simple as the name suggests. We expect something to work as expected and we check if it does. It can be your homework, task or anything which you wanna check for something expected. And in our case, we want our program to work as expected, so we test it.

Why test?

Most of you could say, “Hey, we can manually check for that. Why write a separate program to check another program?” Yeah, What you are thinking is right but only for small programs. We could easily check for issues if our code is only a few lines. But think of a program with more than 1000 lines with asynchronous functions, values jumping from one part of the program to the other, etc. In this case, even a small mistake in naming a variable or typo could make the program behave unexpectedly. And it would be a nightmare debugging the logic and 1000 lines of code.

At the end of the day, the problem can be a simple typo. LOL!

So this is where we might wanna write tests for our code.

How to test?

We use libraries for testing. Some may be inbuilt and some may need to be added as a package. And this depends on the programming language we use or the application we wanna test.

How testing is done in JavaScript?

There are various libraries for testing JavaScript code like Mocha, Jest, etc. And in this article, we will be using Jest for testing though you can use Mocha or any other libraries you like.

What is Jest?

Jest is a testing library for JavaScript and it’s developed by Facebook for use within ReactJS (which is also developed by them). And hence Jest came out. Jest is built-in with React but for other JS applications, we might wanna add it as a package from NPM.

How to setup Jest?

For this example, we will not dive deep into advanced Jest functionalities but keep it simple with just a few basic tests.

So, for the setup, we need NPM and Node. So if you haven’t installed it on your system, go on and install. If you have it, then proceed.

  1. Create a folder with any name you like. Am going to create a folder with mkdir test-js and cd into it cd test-js.
  2. Since we will be installing Jest as a package, we need to initialize our folder with NPM with npm init -y.
  3. We can now add Jest with npm install --save-dev jest. We need to add it as a developer dependency and hence we use the flag --save-dev.
  4. In your package.json file, you might need to change the test script command as jest so we can just run npm test whenever we need to test our code.
  "name": "test-js",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jest": "^24.9.0"

5. Now, we can create our JavaScript file named functions.js to write our code which will be tested using Jest.

6. And to write our tests we need to create a file functions.test.js.

Note that we need to have our test file similar to the name of the JavaScript file we wanna test except adding a .test in-between.

And that’s it. We are now ready to get started writing code and tests.

How to write tests?

Writing Javascript

In our functions.js file, let us write some code to test.

const functions = {
  sum: (a, b) => {
    return a + b
  subtract: (a, b) => {
    return a - b
  copyArray: (a) => {
    return [... a]

module.exports = functions

We have an object containing a few functions and we export the code using module.exports = functions to import the object into our test file which is to be written.

Note that functions in module.exports is not the filename. Instead, it’s the name of the object we have declared. And you can write down the functions separately too instead of using an object. But don’t forget to export each of them.

Writing tests

Now that we have three functions written, let us test it using Jest.

I know it’s too simple to write tests for the fucntions I have. But let’s make it simple for now. Later you can write some complex functions on your own better than me :)

Okay. So in our functions.test.js file,

const functions = require('./functions.js')

test('adds properly', () => {
    expect(functions.sum(1, 5)).toBe(6)

test('subtracts properly', () => {
    expect(functions.subtract(1, 2)).toBe(-1)

Note that we haven’t included the copyArray function in our test and that’s because we have something to talk about it later.

Now run npm test and hurray!🏆 That’s it! We have our tests now. You may see the test pass in the terminal and it’s expected as we have our functions & tests bug-free.

But we haven’t explained what’s there in the test. So let us break down the code now.

What’s there in the test file?
  • In our test file, the first thing we wanna do is to import the module that is needed from our JavaScript file. In our case, we exported the functions object. So let us import that using const functions = require('./functions.js'). Now our test file knows the functions inside our object from the functions.js file.
  • Then we have a function called test which has two params. The first one is simply a string that defines what we wanna do/ what the test is gonna do. The second param is again a function.
  • In the function, we expect something to be something. And in our case, we expect the add function to return the sum of whatever the params we pass to it. So expect(functions.add(1, 5)).toBe(6) is the test case we have defined for our add function.
  • Similarly, we expect the results to be something for the subtract function too.

That is a raw explanation of what’s written there. But there are several terminologies that Jest has which we need to understand.

  • test
  • expect
  • matches (toBe, not.toBe, toEqual, etc)


‘test’ is simply a keyword in Jest. We write tests by using a function provided by Jest called test. It takes in two parameters, a string of what the test is gonna do and another function where we write our actual test. The syntax goes by,test("", () => {})

  • The first parameter is simply a definition of what the test is going to do.
  • The second parameter which is a function takes in the actual testing stuff. We use ‘expect’ and ‘matchers’ within this function.


‘expect’ is also a keyword in Jest. As the name suggests, we expect something from our function or the code we have written. The overall syntax goes by, expect().matcher()

  • Within the expect function, we provide the inputs for our code from which we are expecting something.
  • .matcher is where we use different matchers like toBe, toEqual, etc. Consider these as the conditions the result from expect needs to match. It’s more of a kind of ‘==’.


‘matchers’ is not a keyword in Jest but is used to call a collection of methods in Jest. There’s a whole lot of matchers in Jest such as,

  • toBe
  • toEqual
  • toBeDefined
  • toBeFalsy, etc.

You can find a whole lot of them here.

A typical example would be the one we used in our test file, expect(functions.add(1, 5)).toBe(6). Here, the matcher used is toBe. In more simple terms, we are just doing a check like, is ‘1+5 == 6`? If so, we get the test passed.

Note that there are various matchers available in Jest and it’s impossible to mention everything here. So have a look at their documentation. It’s pretty simple and self-explanatory. The only thing you need to know is which matcher to use where.


Remember we haven’t written a test for the copyArray function? Cause for this test, we will be using a different matcher called toEqual. So our test would be,

test('copies a new array', () => {
  let arr = [1, 2, 3]

In this example, we used toEqual instead of toBe because, in our function from the JavaScript file,

copyArray: (a) => { return [... a] }

we used the spread operator [... a]. And this would copy the contents of the array a we passed and returns a new array. So, if we use toBe, the compiler throws an error since the elements might be the same but not the location. The new array is created in a different location with the same elements of the array we passed on to the function. Hence we need to use toEqual to check accordingly and exactly.

Unit testing

What we have done is called Unit testing which is testing the lowest fundamental blocks or units of code. And that’s why using a test-driven approach is often better than manual testing as each and every fundamental block of the code is tested and verified.

Since our example code is only a few functions, it’s already a unit size. But for large programs, testing each smallest unit of the code is necessary and is what makes unit testing useful before going for production. We don’t want bugs!

And that’s it. We have now learned the low-level basics of Jest. There is more advanced stuff like asynchronous testing, snapshots, etc which we will talk about some other day. Until then, try some testing on your own with maybe some better functions than me :) See ya! 👋