Jest is awesome! It has mocks/spies, test coverage, before/after hooks, assertion library and is very easy to use. Authors of the Jest speak about it as "A delightful JavaScript Testing Framework with a focus on simplicity". So, if you are learning how to create unit tests in JavaScript, this tutorial is for you!
This video is not a comparison of different test frameworks for Node.js, like "Mocha" vs "Jest" vs Jasmine". Instead, we try to use the simple "FizzBuzz" function as an example to demo most of the Jest features. This tutorial is aimed at beginners, but even js-masters might find certain things useful. So, sit tight and let's learn how to write unit tests!
Check out my other "Learn X in Y minutes" videos:
• Learn X in Y minutes
List of all things we cover:
creating a new npm project "npm init", adding dependencies to the package.json, and adding the first test
grouping files together by using describe
writing good human-readable test names
using "test" & "it" aliases
using ".only" to isolate and run only one test
using ".skip" to not run certain tests
data-driven testing with three different approaches
using mocks & spies to not rely on code that we don't control
clearing state of the Jest mock functions with "jest.clearAllMocks()"
using hooks to add code that runs beforeAll, beforeEach, afterEach, and afterAll tests
running tests in a "watch mode" that automatically reruns your tests when implementation or test code changes
using interactive mode for more flexible selection of the tests with a regex pattern, or only re-running failed tests
gathering code coverage to find weak spots (and even achieving 100% coverage!)
finding rogue async code that could be running after the test framework has finished using "detectOpenHandles" flag (helpful for race conditions, unresolved async HTTP calls, open DB connections, etc.)
-----------------------------------------------------------------------------------------------
---------- Timeline -------------------------------------------------------------------
-----------------------------------------------------------------------------------------------
0:00 - intro
0:25 - why jest
1:26 - creating the first test
5:08 - grouping tests
8:00 - it/test alias
8:30 - running only one test
9:32 - skipping tests
9:56 - data-driven tests - primitives
9:56 - data-driven tests - objects
13:26 - data-driven tests - table
16:00 - mock & spy functions
20:14 - before/after hooks
22:48 - watch mode
24:16 - interactive mode
24:49 - test coverage
26:01 - find async code that is not finished properly