2 A first unit test

This chapter covers

  • Writing your first test with Jest
  • Test Structure & Naming Conventions
  • Working with the Assertion APis
  • Test Refactoring and reducing repetitive code

When I first started writing unit tests with a real unit testing framework, there was little documentation, and the frameworks I worked with didn’t have proper examples. (I was mostly coding in VB 5 and 6 at the time.) It was a challenge learning to work with them, and I started out writing rather poor tests. Fortunately, times have changed. In JavaScript, and in practically any language out there, there’s a wide range of choices and plenty of documentation and support from the community to try out these bundles of helpfulness.

in the previous chapter we wrote a very simplistic home-grown test framework. In this chapter we’ll take a look at Jest as our framework of choice for this book.

2.1   About Jest

Jest is an open source test framework created by Facebook. It was originally created for testing frontend React components in JavaScript. These days it’s widely used in many parts of the industry for both backend and frontend projects testing. It supports two major flavors of test syntax (one that uses the word ‘test’ and and another that is based on the ‘Jasmin’

 Syntax – a framework that has inspired many of Jet’s features). We’ll try both of them to see which one we like better.

Jest is easy to use, easy to remember, and has lots of great features.

2.1.1   Preparing our environment

2.1.2   Preparing our working folder

2.1.3   Installing Jest

2.1.4   Creating a test file

2.1.5   Executing Jest:

2.2   The Library, the Assert, the Runner & the Reporter

2.3   What unit testing frameworks offer

2.3.1   The xUnit frameworks

2.3.2   XUnit, TAP and Jest Structures

2.4   Introducing the Password Verifier Project

2.5   The first Jest test for verifyPassword

2.5.1   Testing the test

2.5.2   U.S.E Naming

2.5.3   String comparisons and maintainability

2.5.4   Using describe()

2.5.5   Structure can imply context

2.5.6   The ‘It’ function

2.5.7   Two Jest Flavors

2.5.8   Refactoring the Production Code

2.6   Trying the beforeEach() route

2.6.1   beforeEach() and scroll fatigue

2.7   Trying the factory method route

2.7.1   Replacing beforeEach() completely with factory methods.

2.8   Going Full Circle to test()

2.9   Refactoring to parameterized tests

2.10   Checking for expected thrown errors

sitemap