jest unit test - Fundamentals

Posted by ConnorSBB on Sun, 23 Jan 2022 18:48:28 +0100

jest test - Basic

1, Understanding front-end automation

With the development of front-end, the field of front-end design has become more and more complex. This puts forward higher requirements for our front-end engineering ability. Good front-end engineering generally includes three aspects:

  • Front end automated testing (prerequisites)
  • High quality code design
  • High quality code implementation

2, Mainstream front-end test framework in the market

  1. Jasmine: JavaScript test framework (BDD integrated test development framework), which is also a relatively early test framework;
  2. MOCHA (MOCHA): it is a functional JavaScript testing framework running on node JS and browser, making asynchronous testing simple and interesting. It is also a very excellent framework;
  3. Jest: at present, the most popular front-end testing framework is used by almost all large Internet companies in China;

3, Advantages of jest front end test framework

  • Relatively new: it's human nature to like the new and hate the old. After the new technology comes out, we always want to try it
  • Good foundation: good framework foundation means good performance, multiple functions and easy to use. You can rest assured in these three aspects. Absolutely a good hand. It's done.
  • Fast speed: test the function of A separate module. For example, there are two modules A and B, which have been tested before. At this time, you only change module A for one test. Module B will not run again, but directly test module A. It's like going to the "big sword". All your technicians have tried it once. Next time you come back, just find the best one. You don't have to test it again. (peace of mind)
  • Simple API: look at the official website and you will find that the API is very simple and the number is small.
  • Good isolation: there will be many test files waiting for us to use in Jest. The execution environment of Jest is isolated, so as to avoid errors caused by mutual influence during the execution of different test files.
  • IDE integration: Jest can directly integrate with many editors (VSCode) to make testing easier.
  • Multi project parallelism: for example, we wrote node JS background project. A foreground project is written with React. Jest supports them to run in parallel, which improves our efficiency.
  • Quick out coverage: (test code coverage) for the test of a project, the coverage is required. Jest can quickly produce such coverage statistical results, which is very easy to use.

4: Test difference

  • Unit testing: unit testing refers to the inspection and verification of the smallest testable unit in the software. The unit test mentioned in the front end is to test a module. In other words, when testing the front end, the thing you test must be a module.
  • Integration testing: also called assembly testing or joint testing. On the basis of unit test, all modules are assembled into subsystems or systems according to relevant requirements for integration test.

5, Environment setup + initialization configuration

  1. Initialize a project npm init
  2. Install the jest framework, because this is only developed using yarn add jest -D
  3. npx jest --init or global installation jest initialization

6, Basic must know method

  • Test method: a test method encapsulated by Jest. Generally, two parameters, description and test method, are filled in. This is the smallest unit of the test and nesting is not allowed
  • Expect method: the expected method is what method you call, what parameters you pass, and what you expect (explained in detail in the code).
test('test',() => {
	expect("1").toBe("1");
})

7, Basic configuration and coverage file details

1.jest.config.ts

export default {
  clearMocks: true, // Clear mock every time you run
  collectCoverageFrom: ['src/*.{js,ts}', 'src/**/*.{js,ts}'], //Coverage file
	coverageDirectory: 'coverage', // File name for generating coverage
	coverageProvider: 'v8', 
	coverageThreshold: { // Coverage threshold
    global: {
      branches: 90,
      functions: 95,
      lines: 95,
      statements: 95,
    },
 },
 moduleFileExtensions: ['ts', 'tsx', 'js', 'json', 'jsx', 'node'], // File extension
 preset: 'ts-jest', //ts
 setupFilesAfterEnv: [ // The startup file of each test, similar to main ts
    "<rootDir>/__tests__/boot.ts"
 ],
 testEnvironment: 'jest-environment-jsdom', // js
 testRegex: '(/__tests__/.+\\.(test|spec))\\.(ts|tsx|js)$', // File to test
};

2,package.json startup configuration,

"scripts": {
    "test": "jest",
    "test:w": "jest --watchAll",
    "test:c": "jest --coverage", //  Generate coverage file
  },

3. Run yarn test: C

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files   |     100 |    89.47 |     100 |     100 |
 01demo.js  |     100 |       50 |     100 |     100 | 2
 03es6.js   |     100 |       50 |     100 |     100 | 2
 04async.js |     100 |      100 |     100 |     100 |
 05hook.js  |     100 |      100 |     100 |     100 |
------------|---------|----------|---------|---------|-------------------

Test Suites: 6 passed, 6 total
Tests:       28 passed, 28 total
Snapshots:   0 total
Time:        9.378 s, estimated 11 s
Ran all test suites.
✨  Done in 10.55s.
  • %stmts is statement coverage: is every statement executed?

  • %branch coverage: is every if code block executed?

  • %Funcs function coverage: is every function called?

  • %Lines line coverage: is each line implemented?

    In professional terms, the blocks contained in describe are called suite, and the blocks contained in it/test are called specification, also referred to as spec. a suite can contain multiple specs, but structural semantics should also be paid attention to.

Code reference github address

Original is not easy, free reprint, keep the source

Topics: Front-end Operation & Maintenance unit testing Testing Jest