Introduction to Jest testing framework Painless JavaScript Testing - - PowerPoint PPT Presentation

introduction to jest testing framework
SMART_READER_LITE
LIVE PREVIEW

Introduction to Jest testing framework Painless JavaScript Testing - - PowerPoint PPT Presentation

Introduction to Jest testing framework Painless JavaScript Testing platform Vasyl Boroviak Transform your inspection process with smart, mobile forms. checklists into digital forms and access them on site, in the field, where Typical set of


slide-1
SLIDE 1

Introduction to Jest testing framework

Painless JavaScript Testing platform

slide-2
SLIDE 2

Vasyl Boroviak

Transform your inspection process with smart, mobile forms. checklists into digital forms and access them on site, in the field, where

slide-3
SLIDE 3

Typical set of modules in all my projects

  • mocha/tape (unit tests)
  • chai/tape (assertions)
  • sinon (mocks/spies)
  • istanbul (coverage)
  • proxyquire (JS files mocks)
slide-4
SLIDE 4

Typical set of modules in my new projects

  • jest (unit tests, assertions, mocks, coverage, live test

reload, JS file mocks)

slide-5
SLIDE 5

One of Jest's philosophies is to provide an integrated “zero-configuration”

  • experience. We want to make it as

frictionless as possible to write good tests that are useful. We observed that when engineers are provided with ready- to-use tools, they end up writing more tests, which in turn results in stable and healthy code bases.

slide-6
SLIDE 6

My typical project structure

src/ converters/ api-to-db.js db-to-api.js server.js routes.js model.js db.js node_modules/ test/ converters/ api-to-db.js db-to-api.js server.js routes.js model.js db.js package.json

} }

I usually copy the src/ directory structure inside the test/ directory.

Do you?

I find it hard to maintain and navigate especially in large projects (say, more than 20 source files).

Do you?

slide-7
SLIDE 7

A better project structure

src/ converters/ __tests__/ api-to-db.js db-to-api.js api-to-db.js db-to-api.js __tests__/ server.js routes.js model.js db.js server.js routes.js model.js db.js node_modules/ package.json

Facebook promote the idea that tests should be kept closer to the code it’s testing.

}

slide-8
SLIDE 8

Jest default test folder

By default Jest searches all the directories named __tests__ and runs all JS files inside.

slide-9
SLIDE 9

Jest module mocks (off by default)

Jest will search all the file/module mocks in __mocks__. Mocked:

  • ‘./db’ local file
  • ‘express’ npm module
  • ‘fs’ node module

src/ __mocks__/ db.js __tests__/ server.js routes.js model.js server.js routes.js model.js db.js __mocks__/ express.js fs.js node_modules/ express/ package.json

slide-10
SLIDE 10

jest —-watch

slide-11
SLIDE 11

Jest is fast!

  • Runs tests in parallel processes to minimize test runtime.
  • Runs the previously failed tests first.
  • Automatically find tests related to changed files to

execute in your project.

slide-12
SLIDE 12

Jest global variables

  • afterAll
  • afterEach
  • beforeAll
  • beforeEach
  • check
  • describe
  • expect
  • gen
  • it
  • fit
  • jest
  • pit
  • require
  • test
  • xdescribe
  • xit
  • xtest
slide-13
SLIDE 13

Integrated function or property mock/spy API

mockFn = jest.fn(?implementation) Returns a new, unused mock/spy function. Optionally takes a mock implementation. API:

  • mockFn.mock.calls
  • mockFn.mock.instances
  • mockFn.mockClear()
  • mockFn.mockReset()
  • mockFn.mockImplementation(fn)
  • mockFn.mockImplementationOnce(fn)
  • mockFn.mockReturnThis()
  • mockFn.mockReturnValue(value)
  • mockFn.mockReturnValueOnce(value)
slide-14
SLIDE 14

Jest is smart and works with any compile-to-JS language and integrates seamlessly with Babel

Setup steps:

  • npm i -D babel-jest

Done! Jest it will look for babel-jest module and automatically compile JavaScript code using Babel.

slide-15
SLIDE 15

jest --coverage

slide-16
SLIDE 16

coverageThreshold

  • The minimum threshold enforcement for coverage

results.

  • If the thresholds are not met, jest will return failure.
slide-17
SLIDE 17

Module mocking and reloading

jest.mock('../moduleName', () => { return jest.fn(() => 42); }); const moduleName = require('../moduleName'); moduleName(); // Will return '42'; const React1 = require('react'); jest.resetModules(); const React2 = require('react'); React1 !== React2; // These two are separate copies of React

slide-18
SLIDE 18

Error messages are helpful, visual and color

  • coded. Stack traces point

to the source of problems quickly.

slide-19
SLIDE 19

Integrated timer mocks

it('calls the callback after 1 second', () => { const timerGame = require('../timerGame'); const callback = jest.fn(); timerGame(callback); // At this point in time, the callback should not have been called yet expect(callback).not.toBeCalled(); // Fast-forward until all timers have been executed jest.runAllTimers(); // Now our callback should have been called! expect(callback).toBeCalled(); expect(callback.mock.calls.length).toBe(1); });

slide-20
SLIDE 20

Run your tests within a fake DOM implementation (via jsdom) on the command line

Default: “jsdom” Also possible: “node”

No related cat gif found in the universe

slide-21
SLIDE 21

Snapshot testing

it(‘converts DB to API', () => { const data = convertFromDbToApi(someValue); const serializedData = JSON.stringify(data); expect(serializedData).toMatchSnapshot(); }); Run jest -u to update the __snapshot__ files. “One of the most challenging aspects of my project was keeping the input and output files for each test case in sync. Each little change in functionality could cause all the output files to change. With snapshot testing I do not need the output files, the snapshots are generated for free by Jest! I can simply inspect how Jest updates the snapshots rather than making the changes manually.” – Kyle Davis working on fjs.

slide-22
SLIDE 22

Other cool features

  • Sandboxed test files and automatic global state resets

for every test

  • Integrated support for testing with promises and

async/await

  • When you do console.log it automatically prints the

file and line you did it form

slide-23
SLIDE 23

Jest loves React

  • Jest works out of the box for any React project and

comes pre-configured in create-react-app and react- native projects.

slide-24
SLIDE 24

All configuration options

  • automock [boolean]
  • browser [boolean]
  • bail [boolean]
  • cacheDirectory [string]
  • collectCoverage [boolean]
  • collectCoverageFrom [array]
  • coverageDirectory [string]
  • coveragePathIgnorePatterns [array<string>]
  • coverageReporters [array<string>]
  • coverageThreshold [object]
  • globals [object]
  • mocksPattern [string]
  • moduleDirectories [array<string>]
  • moduleFileExtensions [array<string>]
  • moduleNameMapper [object<string, string>]
  • modulePathIgnorePatterns [array<string>]
  • modulePaths [array<string>]
  • notify [boolean]
  • preset [string]
  • resetMocks [boolean]
  • resetModules [boolean]
  • rootDir [string]
  • setupFiles [array]
  • setupTestFrameworkScriptFile [string]
  • snapshotSerializers [array<string>]
  • testEnvironment [string]
  • testPathDirs [array<string>]
  • testPathIgnorePatterns [array<string>]
  • testRegex [string]
  • testResultsProcessor [string]
  • testRunner [string]
  • testURL [string]
  • timers [string]
  • transform [object<string, string>]
  • transformIgnorePatterns [array<string>]
  • unmockedModulePathPatterns [array<string>]
  • verbose [boolean]
slide-25
SLIDE 25

Jest vs AVA

Built-ins:

  • Assertions
  • Parallel execution
  • Watch&run mode
  • Mocks/spies
  • `require()` mocks
  • Browser environment
  • Coverage

Built-ins:

  • Assertions
  • Parallel execution
  • Watch&run mode
slide-26
SLIDE 26

jest-codemods

Automatically convert Tape, AVA, Mocha tests to Jest. Demo!

slide-27
SLIDE 27

If you or your company are looking for a way to unify unit testing across your JavaScript projects then Jest is the way to go.

slide-28
SLIDE 28