Home Web Front-end JS Tutorial What is Jest? Basic usage of Jest

What is Jest? Basic usage of Jest

Oct 18, 2018 pm 02:51 PM
javascript node.js react.js vue.js

The content of this article is about what is Jest? The introduction of Jest related knowledge has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1 What is Jest?

Jest

Jest is an open source JavaScript testing framework from Facebook that automatically integrates assertions , JSDom, coverage reports and other testing tools that developers need, it is a testing framework with almost zero configuration. And it’s very friendly for testing React, also Facebook’s open source front-end framework.

2 Install Jest

2.1 Initialize package.json

Enter the following command in the shell to initialize the front-end project and generate package.json:

npm init -y
Copy after login

2.2 Install Jest and related dependencies

Enter the following commands in the shell to install the dependencies required for testing:

npm install -D jest babel-jest babel-core babel-preset-env regenerator-runtime
Copy after login

babel-jest, babel-core, regenerator-runtime, These dependencies of babel-preset-env are so that we can use the syntax features of ES6 for unit testing. The import method provided by ES6 to import modules is not supported by Jest itself.

2.3 Add the .babelrc file

Add the .babelrc file in the root directory of the project, and copy the following content in the file:

{ 
 "presets": ["env"]
}
Copy after login

2.4 Modify the test in package.json Script

Open the package.json file and change the value of test under script to jest:

"scripts": {
  "test": "jest"
  }
Copy after login

3. Write your first Jest test

Create the src and test directories and related files

Create the src directory in the project root directory, and add the functions.js file in the src directory

Create the test directory in the project root directory , and create the functions.test.js file in the test directory

Jest will automatically find all test files named using .spec.js or .test.js files in the project and execute them. Usually we are writing test files The naming convention to be followed is: the file name of the test file = the name of the module being tested.test.js. For example, the module being tested is functions.js, then the corresponding test file is named functions.test.js.

Create the tested module in src/functions.js

export default {
  sum(a, b) {
      return a + b;
  }
}
Copy after login

Create a test case in the test/functions.test.js file

import functions  from '../src/functions';
test('sum(2 + 2) 等于 4', () => {
  expect(functions.sum(2, 2)).toBe(4);
})
Copy after login

Run npm run test, Jest will print out the following message in the shell:

PASS  test/functions.test.js
  √ sum(2 + 2) 等于 4 (7ms)
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.8s
Copy after login

4. Several commonly used Jest assertions

expect(functions.sum(2, 2)).toBe(4) is an assertion. Jest provides us with the expect function to wrap the tested method and return an object. The object contains a series of matchers to make it easier for us to make assertions. The above The toBe function is a matcher. Let's introduce several commonly used Jest assertions, which involve multiple matchers. The

.not

//functions.test.js
import functions  from '../src/functions'
test('sum(2, 2) 不等于 5', () => {
  expect(functions.sum(2, 2)).not.toBe(5);
})
Copy after login

.not modifier allows you to test the situation when the result is not equal to a certain value. This is almost exactly the same as English syntax and is easy to understand.

.toEqual()

// functions.js
export default {
  getAuthor() {
      return {
            name: 'LITANGHUI',      
            age: 24,
    }
  }
}
Copy after login
// functions.test.js
import functions  from '../src/functions';
test('getAuthor()返回的对象深度相等', () => {
  expect(functions.getAuthor()).toEqual(functions.getAuthor());
})
test('getAuthor()返回的对象内存地址不同', () => {
  expect(functions.getAuthor()).not.toBe(functions.getAuthor());
})
Copy after login

.toEqual matcher will recursively check whether all attributes and attribute values ​​of the object are equal, so if you want to compare application types, please use .toEqual matcher instead of .toBe.

.toHaveLength

// functions.js
export default {
  getIntArray(num) {
      if (!Number.isInteger(num)) {
            throw Error('"getIntArray"只接受整数类型的参数');
    }
        let result = [];    
        for (let i = 0, len = num; i < len; i++) {
      result.push(i);
    }    
    return result;
  }
}
Copy after login
// functions.test.js
import functions  from &#39;../src/functions&#39;;
test(&#39;getIntArray(3)返回的数组长度应该为3&#39;, () => {
  expect(functions.getIntArray(3)).toHaveLength(3);
})
Copy after login

.toHaveLength can be conveniently used to test whether the length of string and array types meets expectations.

.toThrow

// functions.test.js
import functions  from &#39;../src/functions&#39;;
test(&#39;getIntArray(3.3)应该抛出错误&#39;, () => {
  function getIntArrayWrapFn() {
    functions.getIntArray(3.3);
  }
  expect(getIntArrayWrapFn).toThrow(&#39;"getIntArray"只接受整数类型的参数&#39;);
})
Copy after login

.toThorw may allow us to test whether the method under test throws an exception as expected, but what needs to be noted when using it is: we must use a function that will be tested Make a wrapper for the function, just as getIntArrayWrapFn did above, otherwise the assertion will fail because the function throws.

.toMatch

// functions.test.js
import functions  from &#39;../src/functions&#39;;
test(&#39;getAuthor().name应该包含"li"这个姓氏&#39;, () => {
  expect(functions.getAuthor().name).toMatch(/li/i);
})
Copy after login

.toMatch passes in a regular expression, which allows us to perform string type regular matching.

5 Test asynchronous function

Install axios
Here we use the most commonly used http request library axios for request processing

npm install axios
Copy after login

Write http Request function
We will request http://jsonplaceholder.typicode.com/users/1, This is the mock request address provided by JSONPlaceholder

What is Jest? Basic usage of Jest


JSONPlaceholder

// functions.js
import axios from &#39;axios&#39;;
export default {
  fetchUser() {
      return axios.get(&#39;http://jsonplaceholder.typicode.com/users/1&#39;)
      .then(res => res.data)
      .catch(error => console.log(error));
  }
}
Copy after login
// functions.test.js
import functions  from &#39;../src/functions&#39;;
test(&#39;fetchUser() 可以请求到一个含有name属性值为Leanne Graham的对象&#39;, () => {
  expect.assertions(1);  
  return functions.fetchUser()
    .then(data => {
      expect(data.name).toBe(&#39;Leanne Graham&#39;);
    });
})
Copy after login

Above we called expect.assertions(1), which ensures that in asynchronous test cases, an assertion will be executed in the callback function . This is very effective when testing asynchronous code.

Use async and await to streamline asynchronous code

test(&#39;fetchUser() 可以请求到一个用户名字为Leanne Graham&#39;, async () => {
  expect.assertions(1);
    const data =  await functions.fetchUser();
  expect(data.name).toBe(&#39;Leanne Graham&#39;)
})
Copy after login

Of course, since we have installed Babel, why not use the syntax of async and await to streamline our asynchronous test code? But don’t forget that they all need to be called. expect.assertions method.

The above is the detailed content of What is Jest? Basic usage of Jest. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles