search
HomeWeb Front-endJS TutorialWhat is Jest? Basic usage of Jest

What is Jest? Basic usage of Jest

Oct 18, 2018 pm 02:51 PM
javascriptnode.jsreact.jsvue.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

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

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"]
}

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"
  }

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

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

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

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

.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,
    }
  }
}
// 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());
})

.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;
  }
}
// functions.test.js
import functions  from &#39;../src/functions&#39;;
test(&#39;getIntArray(3)返回的数组长度应该为3&#39;, () => {
  expect(functions.getIntArray(3)).toHaveLength(3);
})

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

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

.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

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

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

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
This article is reproduced at:简书. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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 Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool