The installation

Start by initializing a JS project

yarn init -y
Copy the code

Install Jest using YARN

yarn add -D jest
Copy the code

The basic use

Create demo.js and demo.test.js files under the project. The following functions and tests will be written in the corresponding files and will not be mentioned again

Update the script field of package.json

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

To test, first write the code that needs to be tested, then write the corresponding test cases, and finally execute the tests

// Test code
function sum(num1, num2) {
  return num1 + num2
}

module.exports = { sum }
Copy the code
// Test case
const { sum } = require('./demo')

test('Test sum(1, 2) returns 3'.() = > {
  expect(sum(1.2)).toBe(3)})Copy the code

After yarn test is executed, the yarn test command output is displayed

PASS 1. Basic /demo.test.js ✓ Sum (1, 2) = 3 (3 ms)Copy the code

Configure the Babel

Module. exports and require syntax. If your project is a NodeJS project, you can use this syntax directly. But if you are a front-end project and want to use export and import syntax, you need to configure Babel

First install dependencies

yarn add -D babel-jest @babel/core @babel/preset-env
Copy the code

Add.babelrc.js to the root directory

module.exports = {
  presets: [['@babel/preset-env', { targets: { node: 'current'}}}]],Copy the code

Change the previous code to

// Test code
export function sum(num1, num2) {
  return num1 + num2
}
Copy the code
// Test case
import { sum } from './demo'

test('Test sum(1, 2) returns 3'.() = > {
  expect(sum(1.2)).toBe(3)})Copy the code

Run yarn test to test the yarn

Use matching machine

In basic use, we test if sum(sum(1, 2)).tobe (3) returns a value of 3, where expect returns an “expected” object and toBe is a matcher

Ordinary matching machine

In addition to toBe, which is used to determine whether two values are equal, toEqual is used to determine whether the values of objects and arrays are the same

test('Test objects are equal'.() = > {
  expect({ a: 1 }).toBe({ a: 1 }) / / not through
  expect({ a: 1 }).toEqual({ a: 1 }) / / by
})
Copy the code

You can also use.not to test for opposite matches

test('Test for equal values'.() = > {
  expect(1).toBe(2) / / not through
  expect(1).not.toBe(2) / / by
})
Copy the code

digital

The following matchers are used to compare sizes between values

toBeGreaterThan(3) / / is greater than the
toBeGreaterThanOrEqual(3.5) // Greater than or equal to
toBeLessThan(5) / / less than
toBeLessThanOrEqual(4.5) // Less than or equal to
Copy the code

Note that toBeCloseTo is used instead of toEqual for floating-point equality comparisons

test('Floating point number addition'.() = > {
  const value = 0.1 + 0.2
  // expect(value).tobe (0.3) // Do not pass because floating point numbers have a rounding error of 0.30000000000000004
  expect(value).toBeCloseTo(0.3) / / by
})
Copy the code

string

Use toMatch toMatch the specified string, or you can use regular expressions

test('Match the specified string'.() = > {
  expect('mife').toMatch('fe')
})

test('Match regular expression'.() = > {
  expect('i18n').toMatch(/\d/)})Copy the code

Array or iterable

ToContain can be used to check whether an array or iterable contains a particular item

const list = ['a'.'b'.'c'.'e'.'e'.'f']

test('Test for presence of character e'.() = > {
  expect(list).toContain('e')
  expect(new Set(list)).toContain('e')})Copy the code

authenticity

This type of matchers have the following, when necessary to choose the most appropriate

  • toBeNullMatches onlynull
  • toBeUndefinedMatches onlyundefined
  • toBeDefinedwithtoBeUndefinedOn the contrary
  • toBeTruthyMatch any enableifStatement is a true value
  • toBeFalsyMatch any enableifThe statement is a false value

abnormal

If your code needs toThrow an exception under certain conditions, you can use toThrow for this part of the test

function func() {
  throw new Error('something went wrong here! ')
}

test('Test whether an exception is thrown'.() = > {
  expect(func).toThrow()
  expect(func).toThrow(Error)

  // Error messages can also be specified
  expect(func).toThrow('something went wrong here! ')
  expect(func).toThrow(/wrong/)})Copy the code

other

In the above example, you need to execute the test command again after each test case is written. If you are using VScode, you can install the jest plugin orta.vscode-jest

After you write the test case, jEST will automatically execute and give you feedback in the output panel

The resources

Jest official documentation