当前位置:网站首页>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 .

image.png

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 snapshot Occupy the majority , In the unit test of each component, all demo Did it once snapshot. 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 Vite Configuration of 、 converter 、 Parser and plug-in are common , No extra pair jest Configuration of
  • Yes TypeScript / JSX Support out of the box , Write tests like components
  • Multithreading through tinypool Use Worker Threads 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 .
  • watch In mode, it's faster and hotter , It is more friendly when developing unit tests
  • And Jest Almost the same API, Very few differences
  • More clearly C8 Generate test coverage
  • Source code inline testing
  • Very cool GUI
image.png
image.png

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 --ui

Integration 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 ).

image.png

More refreshing log information

image.png

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 .

原网站

版权声明
本文为[PY]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/200/202207172135044743.html