Jest test using JavaScript

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 shellentering the following commands, initialize and generate distal item package.json:


npm init -y
  • 1
  • 2

2.2 Installation Jest and its dependencies

In shellentering 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-jestbabel-coreregenerator-runtime, babel-preset-envThis 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 .babelrcfile

Add in the root directory of the project .babelrcfile and copy the following files:

{
  "presets": ["env"]
}
```
  • 1
  • 2
  • 3
  • 4

2.4 modify package.jsonthe testscript

Open the package.jsonfile, scriptin the testvalue changes as jest:


"scripts": {
  "test": "jest"
}
  • 1
  • 2
  • 3
  • 4

3. Write your first test Jest

Creating srcand testdirectories and related documents

  • Created in the root directory of the project srcdirectory and srcadd the directory functions.jsfile
  • Created in the root directory of the project testdirectory and testcreate a directory functions.test.jsfile

Jest will automatically find the project all use .spec.jsor .test.jstest 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.jscreation module being tested


export default {
  sum(a, b) {
    return a + b;
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

In test/functions.test.jscreate 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 shellprint 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 expectmethod for packaging function to be tested and returns an object, that object contains a series of matcher to make us easier assertion, the above toBefunction 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

.notModifier 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

.toEqualMatch will recursively check all the object attributes and attribute values are equal, so if you want to compare the type of application, use the .toEqualmatch 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

.toHaveLengthCan 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

.toThorwIt 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 getIntArrayWrapFndone, 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

.toMatchPass 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 axiosto the request processing


npm install axios
  • 1
  • 2

Http written request function
we will request http://jsonplaceholder.typicode.com/users/1that 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 asyncand awaitstreamline 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 Babelwhy not in use, asyncand awaitgrammar to streamline our test asynchronous code? But do not forget the need to call expect.assertionsmethods

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)

Source: https://segmentfault.com/a/1190000016232248

Guess you like

Origin www.cnblogs.com/hanzeng1993/p/11647603.html