1 What is Jest?
Jest JavaScript testing framework is a set of open-source Facebook, it automatically integrates assertion, all the test tools JSDom, coverage reports and other developers need, it is a testing framework almost zero configuration. And it is also open source front-end framework React's Facebook tests very friendly.
2 Installation Jest
2.1 Initializationpackage.json
In shell
entering the following commands, initialize and generate distal item package.json
:
npm init -y
- 1
- 2
2.2 Installation Jest and its dependencies
In shell
entering the following commands, dependent on the installation required for testing:
npm install -D jest babel-jest babel-core babel-preset-env regenerator-runtime
- 1
- 2
babel-jest
, babel-core
, regenerator-runtime
, babel-preset-env
This is dependent on several order so that we can use the syntax characteristic of unit testing ES6, ES6 provided by import
way of importing modules, Jest itself is not supported.
2.3 Add .babelrc
file
Add in the root directory of the project .babelrc
file and copy the following files:
{
"presets": ["env"]
}
```
- 1
- 2
- 3
- 4
2.4 modify package.json
the test
script
Open the package.json
file, script
in the test
value changes as jest
:
"scripts": {
"test": "jest"
}
- 1
- 2
- 3
- 4
3. Write your first test Jest
Creating src
and test
directories and related documents
- Created in the root directory of the project
src
directory andsrc
add the directoryfunctions.js
file - Created in the root directory of the project
test
directory andtest
create a directoryfunctions.test.js
file
Jest will automatically find the project all use .spec.js
or .test.js
test file naming and execution, we usually follow when writing a test file naming convention: the file name of the test file = is the test module name + .test.js
, for example, test modules functions.js
, then the corresponding test file is named functions.test.js
.
The src/functions.js
creation module being tested
export default {
sum(a, b) {
return a + b;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
In test/functions.test.js
create a test case file
import functions from '../src/functions';
test('sum(2 + 2) 等于 4', () => {
expect(functions.sum(2, 2)).toBe(4);
})
- 1
- 2
- 3
- 4
- 5
- 6
Run npm run test
, Jest will shell
print out the following message:
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
4. The common assertion several Jest
The above test case expect(functions.sum(2, 2)).toBe(4)
is an assertion, Jest gives us a expect
method for packaging function to be tested and returns an object, that object contains a series of matcher to make us easier assertion, the above toBe
function is the a matcher. We introduce several common Jest assertion, which involve multiple matchers.
.not
//functions.test.js
import functions from '../src/functions'
test('sum(2, 2) 不等于 5', () => {
expect(functions.sum(2, 2)).not.toBe(5);
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
.not
Modifier allows you to test results not equal to a certain value, and that English grammar is almost exactly the same, well understood.
.toEqual()
// functions.js
export default {
getAuthor() {
return {
name: 'LITANGHUI',
age: 24,
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
// 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());
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
.toEqual
Match will recursively check all the object attributes and attribute values are equal, so if you want to compare the type of application, use the .toEqual
match instead .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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
// functions.test.js
import functions from '../src/functions';
test('getIntArray(3)返回的数组长度应该为3', () => {
expect(functions.getIntArray(3)).toHaveLength(3);
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
.toHaveLength
Can easily be used to test string length and array types meets expectations.
.toThrow
// functions.test.js
import functions from '../src/functions';
test('getIntArray(3.3)应该抛出错误', () => {
function getIntArrayWrapFn() {
functions.getIntArray(3.3);
}
expect(getIntArrayWrapFn).toThrow('"getIntArray"只接受整数类型的参数');
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
.toThorw
It can allow us to test whether the test method throws an exception as expected, but when used to note that: we must use a function to be tested to make a packaging function, as explained above getIntArrayWrapFn
done, because otherwise it will function throw led to the assertion failure.
.toMatch
// functions.test.js
import functions from '../src/functions';
test('getAuthor().name应该包含"li"这个姓氏', () => {
expect(functions.getAuthor().name).toMatch(/li/i);
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
.toMatch
Pass in a regular expression, which allows us to carry out a string type of regular match.
5 test asynchronous function
Installation axios
Here we use the most commonly used library http request axios
to the request processing
npm install axios
- 1
- 2
Http written request function
we will request http://jsonplaceholder.typicode.com/users/1
that this is mock request address provided by JSONPlaceholder
// functions.js
import axios from 'axios';
export default {
fetchUser() {
return axios.get('http://jsonplaceholder.typicode.com/users/1')
.then(res => res.data)
.catch(error => console.log(error));
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
// functions.test.js
import functions from '../src/functions';
test('fetchUser() 可以请求到一个含有name属性值为Leanne Graham的对象', () => {
expect.assertions(1);
return functions.fetchUser()
.then(data => {
expect(data.name).toBe('Leanne Graham');
});
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
We call the above expect.assertions(1)
, it can ensure that the asynchronous test case, there is an assertion it will be executed in the callback function. This is very effective in carrying out test asynchronous code.
Use async
and await
streamline the asynchronous code
test('fetchUser() 可以请求到一个用户名字为Leanne Graham', async () => {
expect.assertions(1);
const data = await functions.fetchUser();
expect(data.name).toBe('Leanne Graham')
})
- 1
- 2
- 3
- 4
- 5
- 6
Of course, since we installed Babel
why not in use, async
and await
grammar to streamline our test asynchronous code? But do not forget the need to call expect.assertions
methods
Reference material
[1] Jest official documents ( https://jestjs.io/zh-Hans/)
【2】 Jest Crash Course - Unit Testing in JavaScript https://www.youtube.com/watch?v=7r4xVDI2vho)