javascript
javascript
javascript
  • Lấy vị trí người dùng với javascript
  • [Problem] Lấy key đầu tiên tìm thấy chứa giá trị cần tìm (ok)
  • 🥸Đoạn mã JavaScript để thêm ký tự đặc biệt vào đầu mỗi dòng trong văn bản nhiều dòng (ok)
  • 😍Tạo ra font in đậm và copy đến website để sử dụng (ok)
  • Hiệu ứng mở sách cực đẹp
  • 🤩JS: Scroll Animation using Intersection Observer API 🤩 (ok)
  • 😅Draw svg on scroll Full (ok)
  • 😄Install Linguise on any domain dịch tự động (ok)
  • 😅Sử dụng ajax tạo popup cho các bài viết wordrpess mattervn.com (ok)
  • 😆PWA - beforeinstallprompt toplusgames.com (ok)
  • How to Use the HTML5 Full-Screen API (Again) (ok)
  • [ERROR GAME] fix lỗi không load iframe gamedistribution.com for toplusgames.com (ok)
  • 😅jQuery Plugin To Create Animated Placeholders - placeholderTypewriter (ok)
  • 😍Làm chức năng thông báo khách hàng đăng ký namkhoahanoi.vn (ok)
  • Tencent Captcha Demo (ok)
  • 😉Send Mail same javascript elasticemail (ok)
  • 🥳Các tool phong thuỷ (ok)
  • 😇Nice Select A lightweight Vanilla JavaScript plugin (ok)
  • Merge objects with the same id but sum values of the objects (ok)
  • 😅Page: DOMContentLoaded, load, beforeunload, unload phần 1 (ok)
  • 😍Scripts: async, defer phần 2(ok)
  • 😂Javascript Array chunkArrayInGroups(arr, size)
  • Sequentially Resolve Promises Works, Giải quyết tuần tự các lời hứa hoạt động (ok)
  • Using Async / Await with the Array Reduce Method API (ok)
  • Flatten an array of arrays,merge, làm phẳng một mảng các mảng (ok)
  • 😌Dependent Dropdown Full (ok)
  • 🥳Select Box Change Dependent Options dynamically (JavaScript Object)
  • 🤩Add elements dynamically full (ok)
  • 😅👌Multiple versions jquery (ok)
  • 😍Cách sử dụng jQuery trong sweetAlert2 là chúng ta phải sử dụng didOpen full (ok)
  • 😁😁 mdbgo.io, mdbootstrap.com full (ok)
  • 🤪Chú ý nếu lỗi cảnh báo từ khóa new nếu dùng trong js thường chúng ta sẽ sử dụng trong mudule (ok)
  • 😝reCAPTCHA javascript (ok)
  • Firework Simulator v2 Phao Hoa (ok)
  • Active scroll center (ok)
  • 🤪Sort array of objects by string property value (ok)
  • 😏findIndex, find index in Array object (ok)
  • 😂Sử dụng nhiều toán tử 3, multiple Ternary Operators (ok)
  • 😅A simple and easy to use library that creates fullscreen scrolling websites fullPage.js (ok)
  • Xây dựng ứng dụng CRUD sử dụng Vue.js trong Laravel (ok)
  • [Chart] Morris.js Line & Area Charts,Bar Charts, Donut Charts, graph (ok)
  • [Chart] Chart.js
  • Multi select checkbox table bootstrap (ok)
  • 😀jquery new, jquery old, jquery migrate (ok)
  • Popup slide up from the bottom overflowing other div blocks (ok)
  • ASYNC JavaScript (CALLBACK, PROMISES, ASYNC AWAIT) video (ok)
  • === START jQuery Mobile ===
  • Data Attributes full (ok)
  • Viết một ứng dụng Restaurant Picke sử dụng "back menu" (ok)
  • Viết một ứng dụng thời tiết, Weather sử dụng panel (ok)
  • jQuery Mobile Tutorial w3schools.com (ok)
  • jQuery Mobile
  • jQuery Mobile - Events (ok)
  • Back button in jquery mobile (ok)
  • === END jQuery Mobile ===
  • removeDuplicates, Remove duplicate values from JS array, remove all duplicates an array object (ok)
  • Sử dụng thư viện jquery.hoverdir.js để làm hiệu ứng hover tuyệt đẹp (ok)
  • Modernizr là gì ? Sử dụng nó cho những trình duyệt cũ ra sao? (ok)
  • Nhận biết tính năng CSS: Modernizr hay Feature Queries? (ok)
  • [SALESFORCE] Remote Action function in Visualforce Page (ok)
  • ScrollIt.js menu (ok)
  • Cách sử dụng scrollTo vanilla cực chất 😘 (ok)
  • Một bài toán xử lý bất đồng bộ trong kintone để lấy số requet quá giới hạn (OK)
  • hexagon thư viện tạo avatar Canvas (ok)
  • 😅Sử dụng Object.assign và để copy dữ liệu, edit, input, form (ok)
  • Một cách đặt và gán giá trị trong mảng, object cự ngắn gọn (ok)
  • [LAZY] jQuery.Lazy và tạo background-loading cực chất (ok)
  • Ví dụ Sử dụng sẵn thư viện masonry của wordpres (ok)
  • Ảnh base64 dùng làm src, placeholder (ok)
  • Kiểm tra hình ảnh đã được tải với thư viện imagesLoaded (ok)
  • Check if Function Exists before Calling? (ok)
  • Async/Await Javascript Full Example (ok)
  • Thenables in JavaScript phục vụ cho bài viết trên (ok)
  • Script distance, khoảng cách (ok)
  • Time, Date full (ok)
  • Function getAllDatesOfMonth (ok)
  • How do I make a placeholder for a 'select' box? (ok)
  • Library choise (ok)
  • jQuery - Redirect with post, Get data php (ok)
  • How to pass data from one page to another page html (ok)
  • how to send data onClick() to another php for processing using post or get?
  • draw grid, vẽ grid (ok)
  • Fullscreen Horizontal Page Slider with jQuery and CSS3 - HSlider scroll template html (ok)
  • _.template, UnderscoreJS Templates Full (ok)
  • Character limit on tag type input number (ok)
  • How to set maximum length in input type=number (ok)
  • ========= START JEST =======
  • Getting Started (ok)
  • Using Matchers (ok)
  • Testing Asynchronous Code
  • Setup and Teardown (ok)
  • Mock Functions
  • Jest Platform
  • Jest tutorial
  • Testing trong Javascript với Jest (Phần 1) (ok)
  • Testing trong Javascript với Jest (Phần 2)
  • Giới thiệu về Jest (Delightful JavaScript Testing)
  • Thử nghiệm phát triển theo hướng phản ứng với Jest và Enzyme
  • Cách kiểm tra các thành phần phản ứng với Jest và Enzyme, Phần 1
  • Cách kiểm tra thành phần phản ứng với Jest và Enzyme, Phần 2
  • Jest js mock jquey and lib
  • Unit testing Các thành phần React với Enzyme và Jest
  • Hướng dẫn viết unit test React với Jest và Enzyme (P1)
  • Tôi đã test các React component như thế nào? (phần 2)
  • Test component trong React với Jest
  • Test Component với Jest và Emzyme
  • Tổng quan về unit test cho dự án react redux saga với Jest Part 1
  • ========= END JEST =======
  • ======= START GULP TUTORIAL ======
  • [GULP] Tìm hiểu về Gulp.js
  • [GULP] Gulp Tutorial
  • [GULP] Gulp - Developing An Application (ok)
  • [GULP] Gulp - Combining Tasks (ok)
  • [GULP] Gulp - Watch (ok)
  • [GULP] Gulp - Live Reload
  • [GULP] Gulp - Optimizing CSS and JavaScript
  • [GULP] Gulp - Optimizing Images
  • [GULP] Gulp - Useful Plugins
  • [GULP] Gulp - Cleaning Unwanted Files
  • Đọc thêm những tài liệu trang khác
  • ======= END GULP TUTORIAL ======
  • Prevent form submission on Enter key press, keyCode (ok)
  • Lấy kích thước ảnh gốc image (ok)
  • 😆How to Center Carousel Slider (ok)
  • Putting Dots onto Owl Carousel Instead of below specialtouchgifts.com.au (ok)
  • Cách xây dựng một Full Screen Carousel với Owl.js
  • Lazy load với owl.carousel.js (ok)
  • Show half of the other item on Owl Carousel vinmec.com items: 1.5 (ok)
  • Show half of the other item on Owl Carousel vinmec.com stagePadding (ok)
  • ------------ Start Fetch -----------
  • Using Fetch Full
  • 😅Javascript Fetch JSON PHP Complete FormData phần 1(ok)
  • Một ví dụ quá đỉnh lấy dữ liệu của form submit trong js bằng đối tượng new FormData + php phần 2(ok)
  • Có một sự thật sử dụng async đồng nghĩa với trả về kết quả là PROMISE (ok)
  • 😅Promise.all full (ok)
  • All you need to know about Promise.all
  • [PROMISE] Promise.all()
  • [PROMISE] Tìm hiểu về promise trong ES6
  • [PROMISE] Introduction to Promises
  • jQuery off() Method (ok)
  • How to make HTTP requests with Axios
  • Axios vs Fetch - 2020 nên sử dụng thằng nào với những tính năng mới trong javascript
  • Get and Post method using Fetch API (ok)
  • Sử dụng JavaScript Fetch API với Async/Await (ok)
  • Xử lý lỗi cho fetch trong trường hợp không có kết nối hoặc kết nối lâu (ok)
  • ------------ End Fetch -----------
  • BigDataCloud Free Reverse Geocoding Javascript API Client (ok)
  • Vietmap API
  • 🥰Sử dụng API Giao hàng Nhanh để tính giá cước vận chuyển (ok)
  • photonsearch as you type with OpenStreetMap map (ok)
  • Leaflet - Một thư viện JS mã nguồn mở cho việc xây dụng ứng dụng bản đồ map (ok)
  • Xây dựng popup lấy vị trí map áp dụng pointfinder (ok)
  • Reverse Geocoding Convert Lat Long to Address map (ok)
  • Free Reverse Geocoding Javascript API map (ok)
  • [YAML] In Action Tutorial Series - General - Hướng dẫn sử dụng file YML YAML cơ bản
  • ----------------- Start Notification -----------------
  • Đối tượng caches object caches (ok)
  • Notification (ok)
  • Sử dụng indexedDB (ok)
  • Using the Notifications API (ok)
  • NotificationEvent (chưa có ví dụ :((
  • ServiceWorkerGlobalScope.onnotificationclick (ok)
  • ServiceWorkerRegistration.getNotifications(ok)
  • ServiceWorkerRegistration.showNotification(ok)
  • Giao tiếp giữa các cửa sổ với Window.postMessage API (ok)
  • Window open() Method (ok)
  • ----------------- End Notification -----------------
  • Example Cookie full (ok)
  • Thay đổi class active javascript bằng cách viết hàm (P1)
  • Thay đổi class active javascript bằng cách viết hàm (P2)
  • jQuery Mockjax Plugin (chưa học cách sử dụng)
  • jQuery Ajax X-editable bootstrap plugin (chưa học cách sử dụng)
  • Lọc theo điều kiện (filter) (ok)
  • Các ví dụ về filter
  • jQuery | grep() Method (ok)
  • Hai bài toán so sánh kinh điển trong javascript
  • Function random :)
  • Một cách sử dụng tab trong theme newspaper
  • Hiệu ứng scroll + animation + menu trượt mượt
  • Trigger a CSS animation on scroll xuongkhopbacninh.vn (ok)
  • App Css Loaded (scroll create link) (ok)
  • Hiệu tứng scroll cực chất (ok)
  • App Js Loaded (ok)
  • Sử dụng async và defer full (Oke)
  • Cách sử dụng Thuộc tính async và defer trong JavaScript hay
  • ReferenceError: Can't find variable: requestAnimationFrame
  • Đoạn code check lỗi PHP trong Ajax
  • [SELECT2] Sử dụng Select2 để thay thế select boxes
  • Một cách sử dụng lazyload khi addclass thật khó khăn...
  • Hiệu ứng croll chuột và % cực đẹp :_
  • Tạo chức năng tự động hoàn tất nhập liệu với thư viện jQuery UI Autocomplete (Phần 1)
  • Tạo chức năng tự động hoàn tất nhập liệu với thư viện jQuery UI Autocomplete (Phần 2)
  • JavaScript String split() Method (OK)
  • Sử dụng thư viện displace để làm menu kéo thả (ok):)))
  • Menu cực chất :)))
  • Sử dụng thư viện slick (ok)
  • vertical scroll, Vertical carousel (ok)
  • Google-like Thanos disintegration (ok)
  • Dùng thư viện jspdf
  • Công thức Toán học cho website
  • Fix lỗi tự động làm thay đổi độ cao :( vieclam123.vn :(
  • Sử dụng window.addEventListener để resize và responsive <3
  • Javascript create, read, and delete cookies (ok)
  • Tự động submit bằng javscript :))) (ok)
  • avoid form warning if user clicks refresh (ok)
  • Một cách truy cập phần tử bằng js thông qua id lạ :)))
  • Meta Refresh
  • Truyền dữ liệu từ javascript sang php
    • Sử dụng form để truyền sang php (ok)
    • Truyền giá trị theo file bằng đường dẫn (ok)
    • Dùng json để truyền sang php
  • auto-refresh page once only after first load – Using JavaScript / JQuery
    • auto-refresh page once only after first load – Using JavaScript / JQuery (ok)
  • Sticky Scroller
    • Sticky Scroller phần 1 (ok)
    • Sticky Scroller phần 2 (ok)
    • owl carousel with dotsContainer (Dots + Text) (ok)
    • Owl Carousel 2 Thumbnails plugin (ok)
  • easy_background Background Slideshow (ok) dev.vieclam123.vn
  • scroll cực chất timviec365.vn, vieclam123.vn (ok)
  • Thư viện lightslider-master gần giống với Owl Carousel
  • Thư viện lightGallery để làm những bộ Sưu tập Gallery
  • Tự viết click slide (ok)
  • Draggable & Touch-friendly Slider Carousel In Pure JS (ok)
  • Slider owl được viết dưới dạng Thumnail (0k)
  • jquery.js:5092 [Violation] Added non-passive event listener to a scroll-blocking 'touchstart' (ok)
  • Added non-passive event listener to a scroll-blocking 'touchstart' event (ok)
  • sticky-mobile-menu-burger-menu (ok)
  • How can I add class to the first and last item among the visible items of Owl Carousel 2? (ok)
  • Owl-carousel2 DEMO - items in 2 rows (oke)
  • How can I create a carousel slick with multiple rows? (ok)
  • Một cách sử dụng create <style> để thêm style (ok)
  • Two Rows Olw Carousel (ok) vieclam123.vn
  • Chức năng tự gọi Javascript (ok) tự động auto
  • Click Next Javascript Base (ok)
  • Slider owl được viết dưới dạng Thumnail viết trên jsfiddle (0k)
  • 😆Creating a Countdown Timer, dakhoathienhoa.com.vn (oK)
  • 🥸NumScroller, Counter From Zero To Value - Javascript Animation (ok)
  • Click Button background-hover white (ok)
  • CodePen HomeLazy Loading Images (Ok)
  • Custom Date Javasript (job247.vn)
  • Tooltip
  • button thay đổi thẻ tags button và span trong Owl Carousel thành thẻ khác :)) (ok)
  • Thêm class vào navigation Owl Carousel (ok)
  • Click lần đầu sử event.preventDefault(); lầu sau not event.preventDefault();
  • landscape && landscape (ok)
  • Landscape && Portrait (ok) job247.vn
  • Hammer thư viện JavaScript chạm cho màn hình cảm ứng
  • jQuery Plugin To Add CSS3 Scrolling Effects On Your Web Page - Smoove menu (ok)
  • 😃Auto Expanding Table Of Contents Plugin - Dynamic Content menu (ok)
  • Tornis - watch and respond
  • scroll-manager
  • Xem thêm
  • Hướng dẫn nấu món "Lazy loading image" theo chuẩn 5 sao Google
  • Welcome to jquery-confirm!
    • jQuery Message Box Plugin Demo Page
  • Magnific-Popup Popup img
  • Slider Swiper Slider-Swiper dùng viết slider giống app
  • Magnific Popup Documentation
  • filter search (ok)
  • Is it possible to convert a select menu to buttons? (ok)
  • Changing selected option on button click select (ok) homef.vn hoặc inop.vyanh.net
  • scrooll animation (job247.vn) (ok)
  • Select2 tutorial
    • Single select boxes (ok)
  • [SELECT2] Disabling a Select2 control (ok)
  • Disabling options (ok)
  • placeholder (ok)
  • Hiển thị nút xóa các giá trị đã chọn + allowClear (ok)
  • Đọc dữ liệu từ một mảng, Data sources (ok)
  • Sử dụng database + php (ok)
  • [SELECT2] Sử dụng form + select2 + ajax + get value (ok)
  • Đọc dữ liệu từ nguồn khác sử dụng AJAX (ok)
  • Thiết lập giá trị mặc định ban đầu trên HTML như bình thường (ok)
  • Sử dụng Ajax để tải dữ liệu từ một nguồn khác (ok)
  • change form
Powered by GitBook
On this page
  • Jest
  • Setting up Jest
  • The package.json
  • Jest running tests
  • Testing arithmetic functions with Jest
  • Jest skipping tests
  • Jest parameterized tests
  • Jest beforeAll
  • Jest grouping tests
  • Jest testing Axios

Was this helpful?

Jest tutorial

https://zetcode.com/javascript/jest/

last modified July 7, 2020

Jest tutorial shows how to use Jest framework to perform unit testing in JavaScript applications.

Jest

Jest JavaScript resting framework with a focus on simplicity. Jest was created by Facebook engineers for its React project.

Unit testing is a software testing where individual units (components) of a software are tested. The purpose of unit testing is to validate that each unit of the software performs as designed. A unit is the smallest testable part of any software.

Mocking is technique where code parts are replaced by dummy implementations that emulate real code. Mocking helps achieve isolation of tests. Mocking is primarily used in unit testing.

In our tests we check that values meet certain conditions. The expect() function gives us a number of matchers that let us validate different things, such as toBe(), toBeFalsy(), or toEqual().

In this tutorial we work with Jest in a Node application.

Setting up Jest

First, we install Jest.

$ node -v
v11.5.0

We use Node version 11.5.0.

$ npm init -y

We initiate a new Node application.

$ npm i --dev jest

We install Jest module with nmp i --dev jest.

$ npm i -g jsonserver
$ npm i axios

We are going to use jsonserver and axios too.

The package.json

The test script runs jest.package.json

{
  "name": "jest-test",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "jest --verbose"
  },
  "keywords": [],
  "author": "Jan Bodnar",
  "license": "ISC",
  "devDependencies": {
    "jest": "^24.0.0"
  },
  "dependencies": {
    "axios": "^0.18.0"
  }
}

By default, jest only gives a rudimentary output. To get more information about test runs, we use the --verbose flag.

Jest running tests

Tests are run with npm test command. The test files must have the test term in their names.

$ npm test

> jest-test@1.0.0 test C:\Users\Jano\Documents\js\jest-test
> jest

  PASS  ./math-utils.test.js
  PASS  ./arith.test.js
  PASS  ./arith-params.test.js
  PASS  ./arith-skip.test.js
  PASS  ./string-utils.test.js
  PASS  ./arith-mock.test.js
  PASS  ./users.test.js

Test Suites: 7 passed, 7 total
Tests:       2 skipped, 35 passed, 37 total
Snapshots:   0 total
Time:        5.19s
Ran all test suites.

This is an sample output running tests with Jest. This is a terse output. For more information, we can use the --verbose option.

To run an individual test, we can use the npx jest testname command.

scripts:{
    "test": "jest --verbose ./test-directory"
}

We can configure Jest to run tests in a specified test directory.

Testing arithmetic functions with Jest

The following is a classic scholarly example for demostrating unit testing with Jest.arith.js

const add = (a, b) => a + b;
const mul = (a, b) => a * b;
const sub = (a, b) => a - b;
const div = (a, b) => a / b;

module.exports = { add, mul, sub, div };

We have four basic arithmetic functions in a module.arith.test.js

const { add, mul, sub, div } = require('./arith');

test('2 + 3 = 5', () => {
  expect(add(2, 3)).toBe(5);
});

test('3 * 4 = 12', () => {
  expect(mul(3, 4)).toBe(12);
});

test('5 - 6 = -1', () => {
  expect(sub(5, 6)).toBe(-1);
});

test('8 / 4 = 2', () => {
  expect(div(8, 4)).toBe(2);
});

In arith.test.js, we test the module. The name of the file contains the test term. It is then picked by jest.

test('2 + 3 = 5', () => {
  expect(add(2, 3)).toBe(5);
});

We test the add() method with test() function. The first parameter is the name of the test, the second parameter is the function to be run. We are testing that the add() function returns correct answer for sample data.

$ npx jest arith.test.js
PASS  ./arith.test.js
  √ 2 + 3 = 5 (3ms)
  √ 3 * 4 = 12 (6ms)
  √ 5 - 6 = -1
  √ 8 / 4 = 2 (1ms)

Test Suites: 1 passed, 1 total
Tests:       4 passed, 4 total
Snapshots:   0 total
Time:        10.981s
Ran all test suites matching /arith.test.js/i.

This is the output.

Jest skipping tests

Tests may take considerable time to finish. We can skip some tests if needed.arith-skip.test.js

const { add, mul, sub, div } = require('./arith');

xtest('2 + 3 = 5', () => {
  expect(add(2, 3)).toBe(5);
});

test.skip('3 * 4 = 12', () => {
  expect(mul(3, 4)).toBe(12);
});

test('5 - 6 = -1', () => {
  expect(sub(5, 6)).toBe(-1);
});

test('8 / 4 = 2', () => {
  expect(div(8, 4)).toBe(2);
});

A test can be skipped with skip() or by using the x prefix. In our case, the first two tests are skipped.

$ npx jest arith-skip.test.js
PASS  ./arith-skip.test.js
  √ 5 - 6 = -1 (2ms)
  √ 8 / 4 = 2 (1ms)
  ○ skipped 2 tests

Test Suites: 1 passed, 1 total
Tests:       2 skipped, 2 passed, 4 total
Snapshots:   0 total
Time:        2.323s
Ran all test suites matching /arith-skip.test.js/i.

Two tests were skipped.

Jest parameterized tests

Parameterized tests allow us to run the same test multiple times using different values. This makes our tests more powerful.

For parameterized tests we use the each() global function.arith-param.test.js

const { add, mul, sub, div } = require('./arith')

test.each([[1, 1, 2], [-1, 2, 1], [2, 1, 3]])(
  '%i + %i equals %i', (a, b, expected) => {
    expect(add(a, b)).toBe(expected);
  },
);

test.each([[1, 1, 0], [-1, 2, -3], [2, 2, 0]])(
  '%i - %i equals %i', (a, b, expected) => {
    expect(sub(a, b)).toBe(expected);
  },
);

test.each([[1, 1, 1], [-1, 2, -2], [2, 2, 4]])(
  '%i * %i equals %i', (a, b, expected) => {
    expect(mul(a, b)).toBe(expected);
  },
);

test.each([[1, 1, 1], [-1, 2, -0.5], [2, 2, 1]])(
  '%i / %i equals %i', (a, b, expected) => {
    expect(div(a, b)).toBe(expected);
  },
);

In these tests, we run each arithmetic function multiple times with different input data.

test.each([[1, 1, 2], [-1, 2, 1], [2, 1, 3]])(
  '%i + %i equals %i', (a, b, expected) => {
    expect(add(a, b)).toBe(expected);
  },
);

The each() method receives an array of arrays with the arguments that are passed into the test function for each row. The %i are format specifiers that expect integers. This is for output that is shown with --verbose option.

$ npx jest arith-params.test.js
PASS  ./arith-params.test.js
  √ 1 + 1 equals 2 (3ms)
  √ -1 + 2 equals 1 (1ms)
  √ 2 + 1 equals 3
  √ 1 - 1 equals 0
  √ -1 - 2 equals -3
  √ 2 - 2 equals 0
  √ 1 * 1 equals 1 (1ms)
  √ -1 * 2 equals -2
  √ 2 * 2 equals 4
  √ 1 / 1 equals 1 (1ms)
  √ -1 / 2 equals 0
  √ 2 / 2 equals 1

Test Suites: 1 passed, 1 total
Tests:       12 passed, 12 total
Snapshots:   0 total
Time:        1.759s
Ran all test suites matching /arith-params.test.js/i.

This is the output.

Jest beforeAll

The beforeAll() function is part of a test setup. It runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests.math-utils.js

const sum = (vals) => {
        
    let sum = 0;
    
    vals.forEach((val) => {
        sum += val;
    });
    
    return sum;
}

const positive = (vals) => {

    return vals.filter((x) => { return x > 0; });
}

const negative = (vals) => {

    return vals.filter((x) => { return x < 0; });
}

module.exports = { sum, positive, negative };

We have a math-utils module, which contains three functions: sum(), positive(), and negative().math-utils.test.js

const { sum, positive, negative } = require('./math-utils');

let vals;
let sum_of_vals;
let pos_vals;
let neg_vals;

beforeAll(() => {
    pos_vals = [2, 1, 3];
    neg_vals = [-2, -1, -1];
    vals = pos_vals.concat(neg_vals);
    sum_of_vals = vals.reduce((x, y) => x + y, 0);
})

test('the sum of vals should be 2', () => {
    expect(sum(vals)).toBe(sum_of_vals);
});

test('should get positive values', () => {
    expect(positive(vals)).toEqual(pos_vals);
});

test('should get negative values', () => {
    expect(negative(vals)).toEqual(neg_vals);
});

In the test file, we use the beforeAll() function to initialize test data before the tests are run.

test('should get positive values', () => {
    expect(positive(vals)).toEqual(pos_vals);
});

To test the positive() function, we use the toEqual() matcher. We test that the function returns an array of positive values equal to the predefined test array of values.

Jest grouping tests

In Jest, tests are grouped into units with describe(). It creates a block that groups together several related tests.string-utils.js

const isPalindrome = (string) => string == string.split('').reverse().join('');

const isAnagram = (w1, w2) => {

    const regularize = (word) => {
        return word.toLowerCase().split('').sort().join('').trim();
    }

    return regularize(w1) === regularize(w2);
}

module.exports = {isPalindrome, isAnagram};

We have string-utils.js module with two functions: isPalindrome() and isAnagram().math-utils.js

const sum = (vals) => {
        
    let sum = 0;
    
    vals.forEach((val) => {
        sum += val;
    });
    
    return sum;
}

const positive = (vals) => {

    return vals.filter((x) => { return x > 0; });
}

const negative = (vals) => {

    return vals.filter((x) => { return x < 0; });
}

module.exports = { sum, positive, negative };

We have again the math-utils.js module.groups.test.js

const { sum, positive, negative } = require('./math-utils');
const { isPalindrome, isAnagram } = require('./string-utils');

describe('testing math utilities', () => {
    let vals;
    let sum_of_vals;
    let pos_vals;
    let neg_vals;

    beforeAll(() => {
        pos_vals = [2, 1, 3];
        neg_vals = [-2, -1, -1];
        vals = pos_vals.concat(neg_vals);
        sum_of_vals = vals.reduce((x, y) => x + y, 0);
    })

    test('the sum of vals should be 2', () => {
        expect(sum(vals)).toBe(sum_of_vals);
    });

    test('should get positive values', () => {
        expect(positive(vals)).toEqual(pos_vals);
    });

    test('should get negative values', () => {
        expect(negative(vals)).toEqual(neg_vals);
    });
});

describe('testing string utilities', () => {

    test.each(["racecar", "radar", "level", "refer", "deified", "civic"])(
        'testing %s for palindrome', (word) => {
            expect(isPalindrome(word)).toBeTruthy();
        },
    );

    test.each([["arc", "car"], ["cat", "act"], ["cider", "cried"]])(
        'testing if %s and %s are anagrams ', (word1, word2) => {
            expect(isAnagram(word1, word2)).toBeTruthy();
        },
    );
});

With describe(), we have created two isolated test groups for string and math utilities. For instance, the beforeAll() is only applied for the math utilities.

$ npx jest groups.test.js
PASS  ./groups.test.js
  testing math utilities
    √ the sum of vals should be 2 (3ms)
    √ should get positive values (1ms)
    √ should get negative values
  testing string utilities
    √ testing racecar for palindrome (1ms)
    √ testing radar for palindrome
    √ testing level for palindrome
    √ testing refer for palindrome
    √ testing deified for palindrome (1ms)
    √ testing civic for palindrome
    √ testing if arc and car are anagrams
    √ testing if cat and act are anagrams
    √ testing if cider and cried are anagrams  (1ms)
 
 Test Suites: 1 passed, 1 total
 Tests:       12 passed, 12 total
 Snapshots:   0 total
 Time:        1.786s
 Ran all test suites matching /groups.test.js/i.

We run the tests.

Jest testing Axios

In the following section, we test JavaScript code that uses Axios library. In the beginning, we have installed axios and json-server modules.users.json

{
  "users": [
      {
          "id": 1,
          "first_name": "Robert",
          "last_name": "Schwartz",
          "email": "rob23@gmail.com"
      },
      {
          "id": 2,
          "first_name": "Lucy",
          "last_name": "Ballmer",
          "email": "lucyb56@gmail.com"
      },
      {
          "id": 3,
          "first_name": "Anna",
          "last_name": "Smith",
          "email": "annasmith23@gmail.com"
      },
      {
          "id": 4,
          "first_name": "Robert",
          "last_name": "Brown",
          "email": "bobbrown432@yahoo.com"
      },
      {
          "id": 5,
          "first_name": "Roger",
          "last_name": "Bacon",
          "email": "rogerbacon12@yahoo.com"
      }
  ]
}

This is some fake data for the JSON server.users.js

const axios = require('axios');

class Users {

     static async all() {
        let res = await axios.get('http://localhost:3000/users');
        return res;
      }
}

module.exports = Users;

The users.js module retrieves data with axios. We will test this module.users-app.js

const Users = require('./users');

async function showData() {
    let res = await Users.all();
    console.log(res.data);
}

showData();
console.log('finished')

The users-app.js is the application that uses users.js module to get and output data.

$ json-server --watch users.json    

We start the json-server.

$ node users-app.js
finished
[ { id: 1,
    first_name: 'Robert',
    last_name: 'Schwartz',
    email: 'rob23@gmail.com' },
  { id: 2,
    first_name: 'Lucy',
    last_name: 'Ballmer',
    email: 'lucyb56@gmail.com' },
  { id: 3,
    first_name: 'Anna',
    last_name: 'Smith',
    email: 'annasmith23@gmail.com' },
  { id: 4,
    first_name: 'Robert',
    last_name: 'Brown',
    email: 'bobbrown432@yahoo.com' },
  { id: 5,
    first_name: 'Roger',
    last_name: 'Bacon',
    email: 'rogerbacon12@yahoo.com' } ]

We run the application.users.test.js

const axios = require('axios');
const Users = require('./users');

jest.mock('axios');

test('should fetch users', () => {

    const users = [{
        "id": 1,
        "first_name": "Robert",
        "last_name": "Schwartz",
        "email": "rob23@gmail.com"
    }, {
        "id": 2,
        "first_name": "Lucy",
        "last_name": "Ballmer",
        "email": "lucyb56@gmail.com"
    }];

    const resp = { data : users };

    axios.get.mockImplementation(() => Promise.resolve(resp));

    Users.all().then(resp => expect(resp.data).toEqual(users));
});

This test file tests the users.js module.

jest.mock('axios');

We mock the module.

const users = [{
    "id": 1,
    "first_name": "Robert",
    "last_name": "Schwartz",
    "email": "rob23@gmail.com"
}, {
    "id": 2,
    "first_name": "Lucy",
    "last_name": "Ballmer",
    "email": "lucyb56@gmail.com"
}];

const resp = { data : users };

This is the response that the mocked module will return.

axios.get.mockImplementation(() => Promise.resolve(resp));

The mocked implementation returns a promise with the response.

Users.all().then(resp => expect(resp.data).toEqual(users));

We test the mocked Users.all() function.

$ npx jest users.test.js
PASS  ./users.test.js
  √ should fetch users (4ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.818s
Ran all test suites matching /users.test.js/i.

We run the test.

In this tutorial, we have used Jest to do unit testing in JavaScript applications.

PreviousJest PlatformNextTesting trong Javascript với Jest (Phần 1) (ok)

Last updated 3 years ago

Was this helpful?