SoFunction
Updated on 2025-04-09

Detailed explanation of TDD and unit test examples in front-end automation testing Vue

1. Getting started with simple use cases

VueProvided@vue/test-utilsLet's help us perform unit testing and createVueWhen checking the test option during the project, it will automatically help us install it

Let’s first introduce two commonly used mounting methods:

  • mount: The component and the subcomponents contained in the component will be mounted
  • shallowMount: shallow mount, only components will be mounted, and sub-components will be ignored

Let’s take a look at a simple test case:

import { shallowMount } from "@vue/test-utils";
import HelloWorld from "@/components/";
describe("", () => {
  it("renders  when passed", () => {
    const msg = "new message";
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg }
    });
    expect(("msg")).toBe(msg);
  });
});

shallowMountWill return onewrapper,thiswrapperThe above will contain many methods to help us test, please refer to:/zh/api/wrap…

2. Snapshot testing

The test case is written as follows: The first test will save a snapshot of the wrapper, and the second time will compare the difference between the current wrapper and the snapshot

describe("", () => {
  it("renders  when passed", () => {
    const msg = "new message";
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg }
    });
    expect(wrapper).toMatchSnapshot();
  });
});

3. Coverage test

Coverage testing is an assessment of the completeness of the test. The more business code the test covers, the higher the coverage.

In we can set collectCoverageFrom to set the file that needs to be tested for coverage

We can test all .vue files and ignore all files under node_modules

Be careful,VueConfigure jest in, refer to:/zh/guides/#…

Then add onescriptThe command can be used to test:

"test:unit": "vue-cli-service test:unit --coverage"

Execute the command to generate a coverage folder, and the Icov-report/ will visually display our test coverage ratio.

4. Test with Vuex

If we introduce Vuex state into the component or use related methods

In test cases, when mounting components, you only need to pass in the vuex store

import store from "@/store/index";
const wrapper = mount(HelloWorld, {
  store
});

The above is the detailed explanation of the TDD and unit test examples in Vue in front-end automation testing. For more information about Vue TDD unit tests, please pay attention to my other related articles!