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

What is Jest? Basic usage of Jest

不言
Release: 2018-10-18 14:52:25
forward
7524 people have browsed it

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!

Related labels:
source:jianshu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template