---
title: How to Build Unit Tests Using Jest
description: Unit tests are a basic building block of quality code. Here's how to quickly build and run them in Jest.
image: https://blog.avenuecode.com/hubfs/pexels-scott-webb-1544944-2.jpg
---

[AvenueCode.com](https://avenuecode.com) [News](https://avenuecode.com/news) [Contact](https://avenuecode.com/contact)

[![Avenue Code Snippets Logo](https://blog.avenuecode.com/hubfs/Avenue%20Code%20New%20Logos%20-%202023/AC-Snippets---Black.png)](https://blog.avenuecode.com/?hsLang=en-us) *menu*

- Technology
  
  [Cloud](https://blog.avenuecode.com/blog/topic/cloud?hsLang=en-us) [Delivery Infrastructure](https://blog.avenuecode.com/blog/topic/delivery-infrastructure?hsLang=en-us) [Web Experience](https://blog.avenuecode.com/blog/topic/web-experience?hsLang=en-us) [Agile Mindset](https://blog.avenuecode.com/blog/topic/agile-mindset?hsLang=en-us) [Quality First](https://blog.avenuecode.com/blog/topic/quality-first?hsLang=en-us)
  
  [Design](https://blog.avenuecode.com/blog/topic/design?hsLang=en-us) [Solution Architecture](https://blog.avenuecode.com/blog/topic/solution-architecture?hsLang=en-us) [Data & ML](https://blog.avenuecode.com/blog/topic/data-and-machine-learning?hsLang=en-us) [Mobile Experience](https://blog.avenuecode.com/blog/topic/mobile-experience?hsLang=en-us)
- [Whitepapers](https://blog.avenuecode.com/blog/topic/whitepapers?hsLang=en-us)
- [Spotlight](https://blog.avenuecode.com/blog/topic/spotlight?hsLang=en-us)
- [Extraordinary Women in Tech](https://blog.avenuecode.com/blog/topic/extraordinary-women-in-tech?hsLang=en-us)
- [Avenue Code Culture](https://blog.avenuecode.com/blog/topic/avenue-code-culture?hsLang=en-us)

- [Cloud](https://blog.avenuecode.com/blog/topic/cloud?hsLang=en-us)
- [Design](https://blog.avenuecode.com/blog/topic/design?hsLang=en-us)
- [Delivery Infrastructure](https://blog.avenuecode.com/blog/topic/delivery-infrastructure?hsLang=en-us)
- [Solution Architecture](https://blog.avenuecode.com/blog/topic/solution-architecture?hsLang=en-us)
- [Web Experience](https://blog.avenuecode.com/blog/topic/web-experience?hsLang=en-us)
- [Data & ML](https://blog.avenuecode.com/blog/topic/data-and-machine-learning?hsLang=en-us)
- [Agile Mindset](https://blog.avenuecode.com/blog/topic/agile-mindset?hsLang=en-us)
- [Mobile Experience](https://blog.avenuecode.com/blog/topic/mobile-experience?hsLang=en-us)
- [Quality First](https://blog.avenuecode.com/blog/topic/quality-first?hsLang=en-us)
- [Whitepapers](https://blog.avenuecode.com/blog/topic/whitepapers?hsLang=en-us)
- [Spotlight](https://blog.avenuecode.com/blog/topic/spotlight?hsLang=en-us)
- [Extraordinary Women in Tech](https://blog.avenuecode.com/blog/topic/extraordinary-women-in-tech?hsLang=en-us)
- [Avenue Code Culture](https://blog.avenuecode.com/blog/topic/avenue-code-culture?hsLang=en-us)

# [How to Build Unit Tests Using Jest](https://blog.avenuecode.com/how-to-build-unit-tests-using-jest)

- [Tweet](https://twitter.com/share)

*perm\_identity* [Luiz Henrique Santos](https://blog.avenuecode.com/how-to-build-unit-tests-using-jest/author/luiz-henrique-santos?hsLang=en-us)

*schedule* 10/12/22 2:00 PM

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](https://jestjs.io/docs/expect). 

##### 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](https://smartbear.com/learn/automated-testing/what-is-unit-testing/)?" SMARTBEAR.

[JestJS.io](https://jestjs.io)

"[Teste unitário com Jest](https://www.devmedia.com.br/teste-unitario-com-jest/41234)" Estevão. DevMedia.<https://www.devmedia.com.br/teste-unitario-com-jest/41234>

---

### 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!

---

### Related Posts

### How Heuristics Can Improve Your Tests

[READ MORE](https://blog.avenuecode.com/how-heuristics-can-improve-your-tests?hsLang=en-us)

### How to Use WireMock for Integration Testing

[READ MORE](https://blog.avenuecode.com/how-to-use-wiremock-for-integration-testing?hsLang=en-us)

### The Best Way to Use Request Validation in Laravel REST API

[READ MORE](https://blog.avenuecode.com/the-best-way-to-use-request-validation-in-laravel-rest-api?hsLang=en-us)

### Leave a Comment!

### Avenue Code Social

[![Facebook Icon](https://blog.avenuecode.com/hubfs/Images/Blog/facebook.png?t=1486470796564)](https://www.facebook.com/avenuecode)

[![Twitter Icon](https://blog.avenuecode.com/hubfs/Images/Blog/twitter.png?t=1486470796842)](https://twitter.com/AvenueCode)

[![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Blog/linkedin.png?t=1486470796556)](https://www.linkedin.com/company/avenuecode/)

### Newsletter

Want to stay on top of all tips and news from Avenue Code?

### Popular Snippets

![Avenue Code-primary versions_logo white avenue code endorsement 2](https://blog.avenuecode.com/hs-fs/hubfs/Avenue%20Code%20New%20Logos%20-%202023/Avenue%20Code-primary%20versions_logo%20white%20avenue%20code%20endorsement%202.png?width=1180&name=Avenue%20Code-primary%20versions_logo%20white%20avenue%20code%20endorsement%202.png "Avenue Code-primary versions_logo white avenue code endorsement 2")

### About Us

- [Who We Are](https://www.avenuecode.com/who-we-are)
- [What We Do](https://www.avenuecode.com/what-we-do)
- [Portfolio](https://www.avenuecode.com/portfolio)
- [Partners](https://www.avenuecode.com/partners)
- [News](https://www.avenuecode.com/news)
- [Events](https://www.avenuecode.com/events)
- [Blog](https://blog.avenuecode.com/)
- [Contact](https://www.avenuecode.com/contact)

### Our Offices

San Francisco

[+1 415 766 4178](tel:+553125161448) [ac.inquiries@avenuecode.com](mailto:brazil.info@avenuecode.com)

Belo Horizonte

[+55 31 2516 1448](tel:+553125161448) [brazil.info@avenuecode.com](mailto:brazil.info@avenuecode.com)

São Paulo

[+55 11 3205 3232](tel:+553125161448) [brazil.info@avenuecode.com](mailto:brazil.info@avenuecode.com)

### We're Hiring!

- [Belo Horizonte](https://www.avenuecode.com/who-we-are)
- [New York](https://www.avenuecode.com/what-we-do)
- [San Francisco](https://www.avenuecode.com/portfolio)
- [São Paulo](https://www.avenuecode.com/partners)

---

©2015 - 2017 Avenue Code

[![Facebook Icon](https://blog.avenuecode.com/hubfs/Images/Icons/facebook-2.png)](https://www.facebook.com/avenuecode) [![Twitter Icon](https://blog.avenuecode.com/hubfs/Images/Icons/twitter-2.png)](https://twitter.com/AvenueCode) [![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Icons/linkedin-2.png)](https://www.linkedin.com/company/avenue-code) [![Glassdoor Icon](https://blog.avenuecode.com/hubfs/Images/Icons/glassdoor-icon-1.png)](https://www.glassdoor.com/Overview/Working-at-Avenue-Code-EI_IE456173.11,22.htm) [![YouTube Icon](https://blog.avenuecode.com/hubfs/Images/Icons/youtube-2.png)](https://www.youtube.com/user/AvenueCodePlay)

Please enable JavaScript to view the [comments powered by Disqus.](http://disqus.com/?ref_noscript)

© 2026 Avenue Code

```json
{
  "@context" : "https://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "Luiz Henrique Santos",
    "url" : "https://blog.avenuecode.com/author/luiz-henrique-santos"
  },
  "dateModified" : "2022-10-12T17:00:00.431Z",
  "datePublished" : "2022-10-12T17:00:00.000Z",
  "headline" : "How to Build Unit Tests Using Jest",
  "image" : [ "https://blog.avenuecode.com/hubfs/pexels-scott-webb-1544944-2.jpg" ],
  "mainEntityOfPage" : {
    "@id" : "https://blog.avenuecode.com/how-to-build-unit-tests-using-jest",
    "@type" : "WebPage"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://blog.avenuecode.com/hubfs/Avenue%20Code%20New%20Logos%20-%202023/Avenue%20Code-primary%20versions_LOGO%20HORIZONTAL%20group%201-7.png"
    },
    "name" : "Avenue Code"
  }
}
```