We all know that code quality is extremely important in the development process, but how can you be sure that your code has it? Manual testing is essential, but for large-scale software deliveries, it may not be enough.

Introduction

One of the best ways to increase code quality is unit tests. They're excellent solutions because you can run a lot of them in a short amount of time, and they are not complex to build. The primary purpose of unit tests is to check the smallest piece of a code, such as a function. There are a few frameworks that can help build these unit tests, and today we'll focus on one called Jest.

What is Jest?

​​Jest is a delightful JavaScript testing framework that focuses on simplicity. It was created by Facebook using the Jasmine framework. Jest is one of the most widespread unit testing tools within the JavaScript community, partly because you can use it on so many frameworks, including Babel, TypeScript, Node, React, Angular,  Vue, and more.

Installation and Configuration

Jest can be installed using Yarn or NPM as a external dependency:

yarn add --dev jest 

or

npm install --save-dev jest

After this, you need to add the code above to your package.json:

{
  "scripts": {
    "test": "jest"
  }
}
Using Jest

Jest offers some common functions, called matchers, that help us perform specific tests. In Jest, the function expect can be used to evaluate a result and return an expectation, where we can apply any matcher. These are some common matches:

  • toEqual => tests equality
  • not => used combined with another matcher but as its opposite
  • toBeNull => tests null
  • toBeTruthy => tests if it is true
  • toBeGreaterThan => tests if a number is greater than
  • toBeLessThan =>  tests if a number is less than
  • toMatch => applies a regular expression to a string
  • toContain => checks if an array contains an item

You can check all matches here

Mock Functions

A unit test should not test all integrations inside a class. Instead, it should isolate the method being tested to check only its logic. To make this possible, Jest enables you to build a mock function or a manual mock to override the dependency.

Let’s pretend we have a function that gets an element top position and scrolls the screen to it:

moveToElement( id ) {
    let el = document.querySelector( id );
    let scrVal = el.getBoundingClientRect().top + document.documentElement.scrollTop;
    window.scrollTo({top: scrVal, behavior: 'smooth'});
}

There are some function calls that are not related to our class, they are from document and window. To isolate our function, we should mock these calls on the unit test using the jest.fn() function. Here's a test class example:

describe( ':methods', () => {
    it( 'move', () => {
        let identifier = 'id1';
        global.document.querySelector = jest.fn( () => ({
            getBoundingClientRect: jest.fn( function() {
                return { top: 100 };
            })
        }) );
        window.scrollTo = jest.fn();
        moveToElement( identifier );
        expect( window.scrollTo ).toBeCalledWith({ behavior: 'smooth', 'top': 100 });
    });
});

In the test above, we first mock the function getBoundingClientRect call inside document to return top:100 when it is called. At the end we assert that window.scrollTo was called with the proper parameters.

Conclusion

Unit tests are a great tool for increasing code quality. Jest is a testing framework that will help you perform unit tests with quality, simplicity, and speed. Jest makes it possible to save time doing manual tests and increase your software reliability.

 

References

"What is Unit Testing?" SMARTBEAR.

JestJS.io

"Teste unitário com Jest" Estevão. DevMedia.


Author

Luiz Henrique Santos

Luiz Henrique Santos is a Full Stack PHP Developer at Avenue Code with 7+ years of experience in IT. He always tries to understand functionalities to propose the best solution while working to deadlines. He applies SOLID standards, develops code that is easy to read and change, and writes unit tests for everything he does!


How Heuristics Can Improve Your Tests

READ MORE

How to Use WireMock for Integration Testing

READ MORE

The Best Way to Use Request Validation in Laravel REST API

READ MORE