“This is the 10th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

What is a Jest

Jest is an enjoyable JavaScript testing framework that focuses on simplicity.

These projects all use Jest: Babel, TypeScript, Node, React, Angular, Vue, and more!

The installation

Install using NPM

npm install --save-dev jest
Copy the code

use

1. Use in webpack

Add the following configuration items to the package.json file

"scripts": {
    "test": "jest"
}
Copy the code

2. Add the object code for the test

We have done the force link algorithm 227. Basic Calculator II, now add a unit test to this algorithm.

File name 46.w0501-calculate.js, code as follows:

Function Calculate (s) {s = s.rim () const len = s.length const stack = [] calculate(s) {s = s.rim () const len = s.length const stack = [] calculate(s) {s = s.rim () const len = s.length const stack = [] For (let I = 0; i < len; [I] i++) {if (s = = = ") continue let TMP = Number (s) [I] / / stitching adjacent array if (! isNaN(tmp)) { num = num * 10 + tmp } if (isNaN(tmp) || i === len - 1) { switch (preSign) { case '': case '+': Stack. Push (num) break case '-': stack. Push (num) break case '-': stack. stack.push(stack.pop() * num) break case '/': Stack. Push (stack. Pop ()/num | 0) break} preSign = s [I] / / write down one operator before num = 0}} / / returns the sum of all elements in the stack the return stack. Reduce ((prev, curr) => prev + curr) } module.exports = calculateCopy the code

3. Create test cases

Then create the calculate.test.js file. Jest will find the file with the test.js extension under the current project and get the test case execution from the file.

Const calculate = require('.. /algorithm/46.w0501-calculate') test('1+1=2', () => { expect(calculate('1+1')).toBe(2) })Copy the code

4. Run the test command

npm run test
Copy the code
The test pass

With luck, here’s what we’ll see

> test > jest PASS __tests__/calculate.test.js ✓ 1+1=2 (2 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 Total Snapshots: 0 Total Time: 1.119s Ran All test suites.Copy the code
Fail the test

This is what happens if you fail the test

> test > jest FAIL __tests__/calculate.test.js ✓ 1+1=2 (2 ms) ✕ calculate(' 10 + 10/2-5 * 9 ') (3 ms) ● Calculate ('), calculate('), calculate('), calculate('), calculate('), calculate('), calculate('), calculate('), calculate('), calculate(') 10 + 10 / 2 - 5 * 9 ') expect(received).toBe(expected) // Object.is equality Expected: -30 Received: 10 7 | 8 | test(`calculate(' 10 + 10 / 2 - 5 * 9 ')`, () => { > 9 | expect(calculate(' 10 + 10 / 2 - 5 * 9 ')).toBe(-30) | ^ 10 | }) at Object.<anonymous> (__tests__/calculate.test.js:9:46) Test Suites: 1 failed, 1 total Tests: 1 failed, 1 passed, 2 total Snapshots: 0 Total Time: 0.976 s, estimated 1 S Ran All Test suites.Copy the code

The following is the printed result

✓ 1+1=2 (2 ms) ✕ Calculate (' 10 + 10/2-5 * 9 ') (3 ms) ✓ 1+1=2 (2 ms) ✕ Calculate (' 10 + 10/2-5 * 9 ') (3 ms)Copy the code
  • called1 + 1 = 2The use case passes
  • calledcalculate(' 10 + 10 / 2 - 5 * 9 ')Did not pass the use case

The following is the printed result

    Expected: -30
    Received: 10

       7 |
       8 | test(`calculate(' 10 + 10 / 2 - 5 * 9 ')`, () => {
    >  9 |   expect(calculate(' 10 + 10 / 2 - 5 * 9 ')).toBe(-30)
         |                                              ^
      10 | })
Copy the code
  • calculate(' 10 + 10 / 2 - 5 * 9 ') Expectations are- 30(Expected: -30) But the actual execution returned10Received: 10), so the use case failed, and indicates that the failed use case is in line 9.

Commonly used API

describe

Equivalent to grouping test cases

describe('outer', () => {
    console.log('describe outer-a');
    
    describe('describe inner 1', () => {
        console.log('describe inner 1');
        test('test 1', () => {
            console.log('test for describe inner 1');
            expect(true).toEqual(true);
        });
    });

    console.log('describe outer-b');
    
    test('test 1', () => {
        console.log('test for describe outer');
        expect(true).toEqual(true);
    });
});
Copy the code
test

Test (arg1, arg2) contains two arguments. The first argument is the description of the test, which allows us to view the result of the use case execution. The second parameter is the logic to be executed by the test, including the normal code and the matcher.

expect

Expect (arg1).tobe (x) is a matcher. When we test a function, we compare the return result of the function with the expected result by the matcher. If they are the same, the current matcher passes. Expect (calculate(‘1+1’)).tobe (2) indicates that the use case will not pass until the result of executing calculate(‘1+1’) and the 2 match are equal.

ToBe uses absolute equality, and toEqual is used when comparing objects.

test('object assignment', () => {
  const data = {one: 1};
  data['two'] = 2;
  expect(data).toEqual({one: 1, two: 2});
});
Copy the code

Commonly used matchers:

  • toBeAbsolutely equal to
  • toEqualWhether is equal to the

Matchers of true and false classes:

  • toBeNullmatchingnull
  • toBeUndefinedmatchingundefined
  • toBeDefinedMatches defined variables
  • toBeTruthymatchingtrue
  • toBeFalsymatchingfalse
  • toBeGreaterThan

Array matcher:

  • toBeGreaterThanIs greater than
  • toBeGreaterThanOrEqualGreater than or equal to
  • toBeLessThanLess than
  • toBeLessThanOrEqualLess than or equal to

String class matcher

  • expect('team').not.toMatch(/I/)Whether the re does not match
  • expect('Christoph').toMatch(/stop/)Match the re

Array type matcher

  • toContainDoes it include

See the official website for more matchers

Detailed instructions please look at the official documentation: www.jestjs.cn/docs/gettin…