test

Testing is a very important regression link in project development. Complete testing can guarantee the code and business and reduce the occurrence of bugs.

In the front-end framework testing can be divided into three types, respectively unit testing, component testing and end-to-end testing, here we mainly explain component testing, component testing in a sense has included unit testing in the inside, click to see more introduction to testing.

chapters

  1. Install dependencies
  2. Creating a Test file
  3. Adding test Configuration

Install dependencies

Vue provides a testing framework Vue Test Utils (VTU for short) for component testing

npm install --save-dev @vue/test-utils@next
Copy the code

The main purpose of VTU is to load Vue components, but not to interpret (compile) components. There are many mature use cases in WebPack, but the scaffolding tool we use is Vite, and Vite does not provide an official test solution, but that’s ok, the Vite community provides many solutions. For example, we will use the plug-in vite-plugin-test next. If you are interested, you can check more solutions in Vite Issue.

Note that webpack explains vue components mainly using VUe-loader + Babel, and vite internal is the use of esbuild to explain JS, through the source code of the viet-plugin-test plug-in can be very intuitive to see how vite is to explain vue components, More detailed implementation principle can be viewed vite source code.

Installing a plug-in

npm install --save-dev vite-plugin-test puppeteer
Copy the code

Creating a Test file

The default tests directory is the tests folder in the root directory.

- ctcode-vue3
	- // Other directories SRC public, etc
    - tests
		- views
			- login.spec.js
Copy the code

Tests contains a views folder, and views contains a login.spec.js file. Since there is only one home page component and one login page component in the project now, the login page component implements the login logic, so the login page is used as the test component. Note that the suffix of the test file is spec.js.

src/tests/views/login.spec.js

//import flushPromises from 'flush-promises'
import {mount} from '@vue/test-utils'
// Import the login page component
import Login from '@/views/Login.vue'
/ / import store
import store from "@/store/index"
// Import the Antd component library completely
import Antd from 'ant-design-vue';

describe('Login.spec.js'.(done) = > {
  it('renders'.async() = > {const wrapper = mount(Login, {
      global: {
        // Load the Vue plugin, because the plugin is loaded in main.js in the project, the test file needs to be imported separately here, equivalent to calling app.use().
        plugins: [store, Antd]
      }
    })
	
    // Form manipulation
    const inputs = wrapper.findAll('input');
    await inputs[0].setValue("admin");
    await inputs[1].setValue("admin")
    await wrapper.find('button').trigger('click');

    // Wait until the DOM updates.
    // await flushPromises()
    
    // Asynchronous request interface and dom refresh latency processing
    setTimeout(() = > {
      const p = wrapper.find(".realname")
      // Assert whether the dom of the real name has two characters
      expect(p.text().length).equal(2)},1000)})})Copy the code

The above test cases mainly test the login business success, first of all, in the form of input admin user name and password input box, and then trigger a click on the submit button to submit the form, asynchronous wait 1 seconds to view the page rendering results are correct, because the user name is randomly generated in the mock two characters, so use string length to determine.

Since the previous code for the login page did not include a rendering of the user’s real name, this feature was added to make it easier for us to verify the test case,

Of course, you should write tests based on components, not change components for testing purposes. At the moment, our project business is not perfect, so let’s focus on how to write tests first.

Modify the login page SRC /views/login.vue

<template>
  <div>
    <h2>Login page -by CTcode</h2>
    <! -- Display user name -->
    <p class="realname">{{store.state.user.info.realname}}</p>
    <a-form layout="inline" :model="formData">
      <a-form-item>
        <a-input
          v-model:value="formData.username"
          placeholder="Username"
        />
      </a-form-item>
      <a-form-item>
        <a-input 
        v-model:value="formData.password" 
        type="password"
        placeholder="Password" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" @click.prevent="onFinish(formData)">The login</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { reactive } from "vue";
import { useStore } from "vuex";
import { message } from "ant-design-vue";

export default {
  setup() {
    const store = useStore();
    
    // Declare the response form data object
    const formData = reactive({
      username: "".password: ""});/** * request login function *@param {object} data* /
    async function onFinish(formData) {
      const result = await store.dispatch("user/login", formData);
      const { data, type } = result.data;

      // After login, the result is processed according to the actual return of background interface
      if(type == "success") {
        message.success('Login successful: welcome${data.user.realname}`)}else {
        message.error("Login failed!")}}return{ formData, onFinish, store }; }};</script>
Copy the code

The above code mainly adds a P tag to display the real name.

Adding test Configuration

Added vite test configuration, creating vite.config.test.js in the root directory

// Import the test plug-in
import viteTestPlugin from 'vite-plugin-test'
import viteConfigFn from "./vite.config"

export default (options) => {

    const config = viteConfigFn(options);

    config.plugins.push(
        viteTestPlugin()
    );

	return config
}
Copy the code

Add a test script command by adding a test command under scripts of package.json

"scripts": {
  "dev": "vite"."build": "vite build"."serve": "vite preview"."test": "vite --config vite.config.test.js"
},
Copy the code

Execute test command

npm run test
Copy the code

Viewing test results

If the test fails, a red fail message is displayed.

Note that our test case includes asynchronous requests, and more asynchronous solutions can be found on the official website.

View the code:

Git clone (downloaded direct checkout https://github.com/chitucode/ctcode-vue3.git git checkout v10.0Copy the code

Wechat account of friends

Add big brother wechat and thousands of peers to enhance technical communication life

hsian_

The last

The code word is not easy and your clicks and likes and comments are my best motivation