resources

Documentation: Vue Test Utils

Reference learning single test items: github.com/holylovelqq…

Jest Unit Test

  • Vue program used in jest/Part1 ~ Part8: www.jianshu.com/u/15631ffb7…
  • Jest grammar article: www.jianshu.com/p/e54218d67…
  • Jest assertion API jestjs. IO /docs/ zh-han…

Some articles:

Blog.csdn.net/sinat_33312…

www.imooc.com/article/254…

Zhuhuix.blog.csdn.net/article/det…

Jestjs. IO/useful – Hans/doc…

Molunerfinn.com/Use-Jest-To…

Juejin. Cn/post / 684490…

Juejin. Cn/post / 686547…

medium.com/@lachlanmil…

zhuanlan.zhihu.com/p/88875020

Jestjs. IO/useful – Hans/doc…

The installation

Install jest and vue-test-utils (document address: vue-test-utils.vuejs.org/zh/) in the vue project. After the installation is successful, the tests folder is generated. The test cases are written under tests/unit and the file ends with the.spec.js suffix. Add script configuration “test:unit”: “vue-cli-service test:unit” to package.json to run single test environment.

Some problems encountered and solutions

Similar questions:

Stackoverflow.com/questions/6…

Stackoverflow.com/questions/4…

Solutions:

constWrapper = shallowMount(component, {propsData,attachTo: document.body
})
Copy the code
  1. Store require. Context problem (vue babel-plugin-require context-hook)

Solution:zhuanlan.zhihu.com/p/88875020Press point 5 for solution

  1. [Vue WARN]: Error in data(): “TypeError: Cannot read property ‘docBaseUrl’ of undefined” Configer not working

Solution:

import { configer } from './xxxxxx.js
import { shallowMount, createLocalVue } from '@vue/test-utils'const localVue = createLocalVue () / / set the configer localVue. The prototype. The configer = configer'
Copy the code

Solution:

// exclude related directories from the jest.config.js configuration file
transformIgnorePatterns: ["/node_modules/(? ! vue-waterfall2)"]

import { shallowMount, createLocalVue } from '@vue/test-utils'
import waterfall from 'vue-waterfall2'

const localVue = createLocalVue()
localVue.use(waterfall)


Copy the code

Solution:

constWrapper = shallowMount(component, {store,stubs: ['AddContent']})Copy the code

The configuration file

// Some test files need to be excluded for some reason
testPathIgnorePatterns: [
  'tests/views/Layout.spec.js'.'tests/views/Workbench/Workbench.spec.js'].// Get custom specifies to check all files that need to be tested
 collectCoverageFrom: [
   'src/**/*.{js,vue}'.// Configure the file to be tested
   '! src/main.js'.// Exclude files and directories
   '! src/plugin/*.js'.'! **/node_modules/**'.'! src/assets/**'.'! tests/**/*.js'].Copy the code

Jest configuration

/** * @module. Exports = {/** * @author XXX * @lasteditor XXX * @lasteditTime xxxx-xx-xx */ module.exports = { moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
  transform: {
      '^.+\\.vue$': 'vue-jest',
      '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub',
      '^.+\\.jsx? $': 'babel-jest'
  },
  transformIgnorePatterns: ['/node_modules/(? ! vue-waterfall2)'],
  moduleNameMapper: {
      '^@/(.*)$': '<rootDir>/src/$1'}, // Specify serialization modules in snapshot: ['jest-serializer-vue'],// Specify the test file range testMatch: ['**/tests/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'], // specify which file collection coverage, or which files are excluded. General entry files app.vue are excluded // Or set files, very simple files, other plug-in files, etc., to exclude collectCoverageFrom: [{js,vue}', // SRC all js/ts/vue files
    '! SRC /main.js', // set file exclusion
    '! src/plugin/*.js',
    '! **/node_modules/**',
    '! src/assets/**',
    '! tests/**/*.js'], // Exclude jest test file: layout.spec.js testPathIgnorePatterns: ['tests/views/Layout.spec.js'
  ],
  coverageDirectory: '<rootDir>/coverage',
  collectCoverage: true,
  coverageReporters: ['lcov', 'text-summary'],
  testURL: 'http://localhost/',
  setupFiles: ['<rootDir>/tests/unit/lib/register-context.js']
}
Copy the code
  • The testMatch section can be written one-sided to specify a certain file to specifically improve unit test coverage for that file.

  • The configuration of collectCoverage and collectCoverageFrom can generate the coverage directory locally. Open the coverage/lcov-report/index.html file to see the specific single-test coverage, as shown in the figure

If you open the file, you can see the current unit coverage and whether the current method is covered, as shown in the figure:What is not covered is circled in red. In the actual single test process, mock different conditions as far as possible and enter different cases, which can greatly improve the single test coverage.

  • Specific single test file writing method (including different situations)
    • Method emulation (Window method, $message method, Promise method)
    • Emulation of plug-ins (Store, Router, subcomponents)
    • Scenario coverage (Data, computed, Watch, Methods, Components)
    • Improved coverage (different cases, assertion methods accessed, dom operations overridden)

Ps: Mock as many different conditions as possible, and enter assertions in different cases, which can greatly improve coverage. If there are case results that cannot be simulated, try to simulate methods to be accessed