This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Vue DevUI is a Vue3 open source component library incubated by the open source community, which means that from the beginning Vue DevUI was not an individual maintenance project, but a continuous evolution through the collective efforts of the community.

Since it is a new project, we always use the latest technology in the selection of technology:

  • withViteSet up foundation engineering and build package
  • With the latestVue3Syntax authoring component
  • withTypeScriptAdd a type system to your code
  • withJSXSyntax writing Vue components ensures maximum flexibility
  • withVitePressDocumentation for building a component library

In the beginning, we just put up a shelf, wrote some components, added commit checks, and the engineering side of things was pretty rudimentary — no unit tests, no ESLint, no CLI tools.

Brenner, a fellow community member, noticed that as an open source project, how could there be no unit tests? After the official release, others a look, there is no unit test, still dare to use?

So On June 13, 2021, Brenner submitted a PR for Vue DevUI, adding a unit Test environment based on Jest and Vue Test Utils.

Let’s take a look at how to set up a unit test environment for the Vue project and add unit tests to Vue components.

1 introduction Jest

1.1 installation Jest

yarn add -D jest @types/jest
Copy the code

1.2 Adding Script Commands

package.json

"Scripts" : {" dev ":" vite ", "build" : "vue - TSC - noEmit && vite build", "serve" : "vite preview", "test", "jest" / / new},Copy the code

1.3 Writing Test Cases

Describe a Test Suite ('tree', () => {// Step 2: describe a Test Suite // I think 'tree should render correctly' it('tree should render correctly', () => {// Step 3: (toContain) 'devui-tree' expect(wrapper.classes()).tocontain ('devui-tree') // Hope (expect) tree components (place) 6 expect the number of child elements (wrapper. Element. ChildElementCount). The place (6)})})Copy the code

1.4 Write your first unit test

devui/tree/__tests__/tree.spec.ts

Describe a Test Suite ('tree', () => {// Step 2: describe a Test Suite // I think 'tree should render correctly' it('should render correctly', () => {// Step 3: Write test assertions expecting 1 equal to 1 expect(1).toequal (1)})})Copy the code

1.5 Running the test command

yarn test
Copy the code

2 Test Components

2.1 installation@vue/test-utils

yarn add -D @vue/test-utils
Copy the code

2.2 Write component test code

devui/tree/__tests__/tree.spec.ts

import { mount } from '@vue/test-utils' import DTree from '.. /src/tree' describe('tree', () => { it('should render correctly', () => { const wrapper = mount({ components: {DTree}, template: '<d-tree :data="data"></d-tree> ', setup() {const data= [{label:' level 1', level: 1, children: [{label: '-1-1', level: 2, children: [{label:' -1-1', level: 3,}]}]}, {label: '-1-1', level: 1, open: True, // Add children: [{label: 'level-2 ', level: 2, children: [{label:' level-2 ', level: 3,}]}, {label: 'level-2 ', level: 2, children: [{label:' level-2 ', level: 3,}]}]}, {label: 'level-2 ', level: 1, open: True, // Add children: [{label: '3-1-1', level: 2, children: [{label:' 3-1-1', level: 3,}]}, {label: // Add children: [{label: '3-2-1', level: 2, open: true,}]}]}, {label:' 3-2-1', level: 2, open: true, // Add children: [{label: '3-2-1', level: 3,}]}]}, {label:' 3-2-1', level: 3,}]}]}, {label: '3-2-1', level: 2, open: true,} 1, }] return { data } } }) expect(wrapper.classes()).toContain('devui-tree') }) })Copy the code

Run the yarn test command again, and an error occurs

3 Problems encountered and corresponding solutions

SyntaxError: Cannot use import statement outside a module

This is a typical syntax problem encountered when jEST parses a file.

The error message also suggests possible causes and methods of reconciliation:

Here's what you can do: • If you are trying to use ECMAScript Modules, See https://jestjs.io/docs/ecmascript-modules for how to enable it. • If you are trying to use TypeScript. See https://jestjs.io/docs/getting-started#using-typescript, and some of your "node_modules" files transformed, You can specify a custom "transformIgnorePatterns" in your config. • If you need a custom transformation specify a • If you simply want to mock your non-js modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.Copy the code

You might import ES6 TypeScript, but not configure the transform converter.

Install Babel – jest

Install dependencies babel-jest and @babel/preset-env first

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

Configuration jest transform

jest.config.js

module.exports = {
  transform: {
    '^.+\\.(ts|tsx|js|jsx)$': [
      'babel-jest', { presets: ['@babel/preset-env'] }
    ]
  },
};
Copy the code

Run the yarn test command again, and an error occurs

3.2 Error 2: Cannot find module ‘vue-template-compiler’

@vue/test-utils is not installed correctly. The default is @vue/test-utils for vue2, but we are vue3 component library and need to install @vue/test-utils@next.

Let’s install vue-template-Compiler as prompted.

The installation relies on vue-template-Compiler

yarn add -D vue-template-compiler
Copy the code

Run the yarn test command again, and a double error message is displayed

3.3 Error 3: Vue Packages Version Mismatch

The vuE-template-compiler is not a problem, but it is a version mismatch.

Install Vue3 version @vue/test-utils@next

yarn add -D @vue/test-utils@next
Copy the code

Run the yarn test command again, and another pair of 叒 errors are found ~

This is followed by a series of syntaxErrors caused by not configuring the appropriate Transform converter.

Error: Unexpected token, expected “,”

Install @ Babel/preset – typescript

yarn add -D @babel/preset-typescript
Copy the code

Configuration @ Babel/preset – typescript

jest.config.js

module.exports = { transform: { '^.+\\.(ts|tsx|js|jsx)$': [ 'babel-jest', { presets: [' @ Babel/preset - env ', '@ Babel/preset - typescript / / new]}}],};Copy the code

An error message is displayed when the yarn test command is executed again

3.5 error 5: SyntaxError: Unexpected token ‘<‘

Install @ vue/Babel – plugin – JSX

yarn add -D @vue/babel-plugin-jsx
Copy the code

Configuration @ vue/Babel – plugin – JSX

jest.config.js

module.exports = { transform: { '^.+\\.(ts|tsx|js|jsx)$': [ 'babel-jest', { presets: [' @ Babel/preset - env ', '@ Babel/preset - typescript'], plugins: [' @ vue/Babel - plugin - JSX '] / / new}}],};Copy the code

If you continue to run the yarn test command, an error message is displayed

3.6 SyntaxError: Invalid or unexpected token

Modify style import

import './tree.scss'

->

import './tree'
Copy the code

Run the yarn test command again, and it is found that 叒 yi is faulty

3.7 Seventh error: ReferenceError: Document is not defined

The error message is clear:

The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.
    Consider using the "jsdom" test environment.
Copy the code

The test environment is incorrect. You need to configure the jsDOM test environment.

Example modify testEnvironment testEnvironment

jest.config.js

testEnvironment: 'jest-environment-jsdom',
Copy the code

Success at last!

This should be a celebration 🎉!

summary

This paper mainly shares the steps of building vuE3 component library unit test environment, problems encountered and corresponding solutions.

  1. The introduction ofjestBasic unit testing is supported
  2. The introduction of@vue/test-utilsSupport unit testing of VUE components
  3. configurationjest.config.js, an increase of@babel/preset-envand@babel/preset-typescripttwopresetTo support theES6andTSGrammar, and one@vue/babel-plugin-jsxThe plugin to supportJSXgrammar
  4. configurationtestEnvironmentforjest-environment-jsdom
  5. Write a trilogy of unit tests:The test set,Unit testing,The test assertion
  6. The typical problems encountered in building unit test environment and corresponding solutions are analyzed

Welcome to build DevUI open source project together

Our DevUI team has a number of open source projects, now we are recruiting contributor, welcome everyone to participate in open source! (If you are interested in DevUI, you can add devui-Official to our core development group.)

  • Ng DevUI: github.com/DevCloudFE/…
  • Vue DevUI: gitee.com/devui/vue-d…
  • DevUI Admin github.com/DevCloudFE/…

DevUI official website: Devui.design /

Also welcome to follow me and the village head “Vue DevUI Open Source Guide” series live!

The Vue DevUI Open Source Guide series is going to be split into two streams:

  1. Component design and implementation
  2. Component library engineering

So far [Component Design and Implementation] has completed 3 phases (not yet finished) :

  1. Vue DevUI Open Source Guide 01: Submit my first PR
  2. [I want to do open source] Vue DevUI open source guide 02: make a respectable Tree component
  3. Vue DevUI open Source Guide 03: Learn to “single test” will have a sense of security! Complete the Tree component!

[Component library Engineering] Has completed phase 2 (in progress) :

  1. Vue DevUI Open source guide 04: component library engineering construction project initialization, JSX support
  2. [I want to do open source] Vue DevUI open source guide 05: Open source component library document construction, VitePress in the process of using the pit experience, overcome these difficulties you will gain a lot!
  3. Vue DevUI Open Source Guide 06: Take you hand in hand to develop a scaffolding

Have reached a consensus with the village head teacherAs long as the village head teacher’s live broadcast room does not fall, as long as there are partners willing to participate in, this series will continue to do!

Let’s make a vuE3 open source component library from 0 to 1!

Every Friday night at 9 o ‘clock, we are in the village chief’s broadcast room, be there or be square!

Address of village head direct broadcast room