当前位置:网站首页>Practice of tDesign in vitest
Practice of tDesign in vitest
2022-07-19 14:49:00 【PY】
origin
stay tdesign-vue-next Of CI In the process , The execution efficiency of unit test module is too low , Every time in unit testing, it costs 6m above . Add dependency according to ,lint Check and other links , Need to spend 8m above .
In addition, we just dealt with the unit test before , There are no corresponding requirements for the components submitted by developers , Just let it run . On the other hand, unit testing is currently TD Release a card point of the official version , So I'm going to comb and restructure it , Prepare for the follow-up key work .
Pain points and current situation
- Unit test execution efficiency is too low , As mentioned above , This speed is unbearable .
- The unit test specification is not clear , Developers have no corresponding single test specifications to follow , I don't know how to write .
- Unit testing
snapshotOccupy the majority , In the unit test of each component, alldemoDid it oncesnapshot. This part of the code is output by the script . To some extent, it belongs to integration testing , But the execution process is integrated into the manually written unit tests , Integration of integration test is needed .
vitest
I first noticed vitest Is in evan you Share inside .vitest Its characteristics are as follows :
- And
ViteConfiguration of 、 converter 、 Parser and plug-in are common , No extra pairjestConfiguration of - Yes
TypeScript / JSXSupport out of the box , Write tests like components - Multithreading through
tinypoolUseWorkerThreads run tests concurrently as much as possible . Isolate the running environment of each test file , Therefore, the running environment change in one file will not affect other files . watchIn mode, it's faster and hotter , It is more friendly when developing unit tests- And
JestAlmost the sameAPI, Very few differences - More clearly
C8Generate test coverage - Source code inline testing
- Very cool
GUI
transfer
Profile modification
rely on , The above said ,vitest Configuration files and vite Configuration file sharing , And plug-ins are also shared , So there is no need to configure jest Configure the same babel-jest, vue-jest, jest-serializer-vue These plug-ins .
development environment
vitest Execution commands in the development environment
vitest --config site/vite.config.js In the process of single test development , You need to filter the corresponding test files , Then you only need to add the corresponding file path , As follows :
# perform button Single test of components
vitest --config site/vite.config.js button
# perform button Of index.test.jsx The test file
vitest --config site/vite.config.js button/index.test.jsx And then there is GUI The option to
vitest --config site/vite.config.js --uiIntegration testing
Previously, we inherited two sets of testing environments ssr The environment and csr Environmental Science .
ssr Environmental Science
Yes ssr Environment testing needs to be done setup Used to make components render, This part is consistent with the previous .
ssr-setup
import { config } from '@vue/test-utils';
import { createApp } from 'vue';
import { renderToString } from '@vue/server-renderer';
import TDesign from '@/src/index';
config.global.plugins = [TDesign];
// global mount createSSRApp Method , mount render Configuration of the environment
config.global.createSSRApp = (comp) => {
const app = createApp(comp);
app.config.globalProperties.$route = {};
app.use(TDesign);
const html = renderToString(app);
return html;
}; The previous execution environment was commonjs The introduction of components uses require, stay vite Need to be replaced with es canonical import
const demo = require(`../.${file}`);ssr.test.js
import glob from 'glob';
import MockDate from 'mockdate';
import { config } from '@vue/test-utils';
MockDate.set('2020-12-28 00:00:00');
function runTest() {
const files = glob.sync('./examples/**/demos/*.vue');
const { createSSRApp } = config.global;
describe('ssr snapshot test', () => {
files.forEach((file) => {
it(`ssr test ${file}`, async () => {
const demo = await import(`../.${file}`); // This part
const realDemoComp = demo.default ? demo.default : demo;
const html = await createSSRApp(realDemoComp);
expect(html).toMatchSnapshot();
});
});
});
}
runTest();csr Environmental Science
csr The integration test of the environment used the script to output the following standard file , Distributed in the unit test of each component . This will affect the execution efficiency of unit tests , Open one for each component describe, These codes will affect the code structure of unit tests . So it is most reasonable to merge in one file . Actually, the realization idea is similar to ssr Almost the same , It's just render It's just different .
/**
* This file is a script `npm run test:demo` Automatic generation , If you need to modify , Execute the script command . Please do not write directly , Otherwise it will be overwritten
*/
import { mount } from '@vue/test-utils';
import baseVue from '@/examples/affix/demos/base.vue';
import containerVue from '@/examples/affix/demos/container.vue';
const mapper = {
baseVue,
containerVue,
};
describe('Affix', () => {
Object.keys(mapper).forEach((demoName) => {
it(`Affix ${demoName} demo works fine`, () => {
const wrapper = mount(mapper[demoName]);
expect(wrapper.element).toMatchSnapshot();
});
});
});csr.test.js
import glob from 'glob';
import MockDate from 'mockdate';
import { mount } from '@vue/test-utils';
MockDate.set('2020-12-28 00:00:00');
function runTest() {
const files = glob.sync('./examples/**/demos/*.vue');
describe('csr snapshot test', () => {
files.forEach((file) => {
it(`csr test ${file}`, async () => {
const demo = await import(`../.${file}`);
const realDemoComp = demo.default ? demo.default : demo;
realDemoComp.name = `test-csr-${realDemoComp.name}`;
const wrapper = mount(realDemoComp);
expect(wrapper.element).toMatchSnapshot();
});
});
});
}
runTest();The configuration file
vitest The configuration file is as follows , The next paragraph config Just hang on vite.config.js Of test Options can be .
const testConfig = {
include:
process.env.NODE_ENV === 'test-snap'
? ['test/snap/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
: ['test/unit/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
globals: true,
environment: 'jsdom',
testTimeout: 5000,
setupFiles: process.env.NODE_ENV === 'test-snap' ? path.resolve(__dirname, '../script/test/test-setup.js') : '',
transformMode: {
web: [/\.[jt]sx$/],
},
coverage: {
reporter: ['text', 'json', 'html'],
},
};Compatibility
Because our old test plan is based on jest, Corresponding API There are . So during the migration , There are only some compatibility problems from jest The function in , Switch to vi, Other problems have not been encountered .
before
const fn = jest.fn();after
import { vi } from 'vitest';
const fn = vi.fn();result
CI Test speed increased
stay CI From the original 6m Upgrade to 2m30, The execution efficiency is increased by% 60%, In the development machine, the execution efficiency is higher ( The execution efficiency of machines with different configurations is different , use ci The implementation of the standard in the comparative test ).
More refreshing log information
jest This part of log Just the log of a single component , And the whole log It's very long to write it down , As a result, we will ignore many log alarms in development . The local terminal The length of output is limited . and vitest Of log Is very refreshing .
- Source portal , Welcome to join
tdesignTo build
边栏推荐
- kube-proxy & Service & Endpoint
- Minuterie logicielle à puce unique v2.0
- CompositionAPI 组件开发范式
- Huawei wireless device configuration dynamic load balancing
- Codeforces Round #808 (Div. 1)(A~C)
- STM32 positioning hardfault location method and encountered situation in keil environment
- MySQL storage functions and triggers
- Display module in pyGame
- ShanDong Multi-University Training #3
- Addition, deletion, modification and query of database
猜你喜欢

ShanDong Multi-University Training #3

Configure spectrum navigation for Huawei wireless devices

滑动窗口最大值问题

ping 命令还能这么玩?

C speech Young's matrix · left-hand string · judge whether the string is rotated
![[flask introduction series] request hook and context](/img/a9/96e330525ee1337daab275b87db892.png)
[flask introduction series] request hook and context

dba
[email protected] Moveactivityidto task fallback special case analysis"/>Learning records [email protected] Moveactivityidto task fallback special case analysis

Matplotlib draw multi line graph (solve the problem that Matplotlib Chinese cannot be displayed)

Classes abstraites et dérivées
随机推荐
CompositionAPI 组件开发范式
MySQL CPU使用率飙升,如何定位是被谁占用了
MVCC多版本并发控制
Analysis of network communication flow of different containers on the same host
Explain the operation of C language file in detail
MySQL read / write separation
The manual is not complete. How to manually dig out the monitoring information of tongweb?
Can ping command still play like this?
【MQTT从入门到提高系列 | 07】MQTT3.1.1之链路保活及断开
滑動窗口最大值問題
Read the paper: temporary graph networks for deep learning on dynamic graphs
Database SQL Server
Labview32-bit and 64 bit compatibility
Data consistency between redis and MySQL
Si446 usage record (III): match function
An unforgettable day in 2022 summer camp
[Axi] interpret the additional signals of the Axi protocol (QoS signal, region signal, and user signal)
Zhikanghu property elderly care service plan
Redis source code and design analysis -- 1 Simple dynamic string
敏捷的第一步:把 “迭代” 变为 “冲刺” 开始!