introduction to jest testing framework
play

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


  1. Introduction to Jest testing framework Painless JavaScript Testing platform

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

  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)

  4. Typical set of modules in my new projects • jest (unit tests, assertions, mocks, coverage, live test reload, JS file mocks)

  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.

  6. My typical project structure I usually copy the src/ directory structure src/ inside the test/ directory. } converters/ Do you? api-to-db.js db-to-api.js server.js I find it hard to maintain and navigate routes.js especially in large projects model.js (say, more than 20 source files). db.js Do you? node_modules/ test/ } converters/ api-to-db.js db-to-api.js server.js routes.js model.js db.js package.json

  7. A better project structure src/ converters/ } __tests__/ Facebook promote the idea that tests api-to-db.js should be kept closer to the code it’s db-to-api.js testing. 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

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

  9. Jest module mocks (off by default) src/ Jest will search all the file/module mocks __mocks__/ in __mocks__ . db.js __tests__/ server.js Mocked: routes.js model.js • ‘./db’ local file server.js • ‘express’ npm module routes.js • ‘fs’ node module model.js db.js __mocks__/ express.js fs.js node_modules/ express/ package.json

  10. jest — -watch

  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.

  12. Jest global variables • afterAll • afterEach • beforeAll • beforeEach • check • describe • expect • gen • it • fit • jest • pit • require • test • xdescribe • xit • xtest

  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)

  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.

  15. jest --coverage

  16. coverageThreshold • The minimum threshold enforcement for coverage results. • If the thresholds are not met, jest will return failure.

  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

  18. Error messages are helpful, visual and color coded. Stack traces point to the source of problems quickly.

  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 ); });

  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

  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.

  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

  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.

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

  25. Jest vs AVA Built-ins: Built-ins: • Assertions • Assertions • Parallel execution • Parallel execution • Watch&run mode • Watch&run mode • Mocks/spies • `require()` mocks • Browser environment • Coverage

  26. jest-codemods Automatically convert Tape , AVA , Mocha tests to Jest . Demo!

  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.

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend