Penguin Geeks | Front-End Automated Testing: A Powerful Tool for High-Quality Product Delivery (Part 2)
Article images may contain Chinese text.

In “Penguin Geeks | Front-End Automated Testing: A Powerful Tool for High-Quality Product Delivery (Part 1),” published a couple of days ago, we gained a thorough understanding of unit testing. Unit tests help us detect problems in code more effectively, reduce bugs, and improve development efficiency.
Today, we will walk through testing methods and techniques for different scenarios and explain how to write test code using common assertion libraries. We will also explain how to generate test reports and summarize the overall testing process to help you better understand and apply unit testing.
Module Testing
Here, modules primarily refer to pages, commonly called the router portion. Testing this portion mainly involves custom component events and verification that the overall UI functions correctly.
Testing Page Structure
The mount, shallowMount, find, and findAll methods can all return a wrapper object. A wrapper exposes many convenient methods for wrapping, traversing, and querying the Vue component instances within it.
Both find and findAll accept a selector as an argument. The find method returns a Wrapper for the DOM node or Vue component matching the selector; findAll returns a WrapperArray containing Wrappers for all DOM nodes or Vue components matching the selector.
Scenario:
Home contains a p tag with the class .outer and the text Aaron.
import Home from "@/pages/Home.vue";
import { mount } from "@vue/test-utils";
describe('Test for Home Page', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(Home);
});
it('get tag dom', () => {
// Use a Vue component selector
expect(wrapper.is(Test1)).toBe(true);
// Use a CSS selector
expect(wrapper.is('.outer')).toBe(true);
// Use a CSS selector
expect(wrapper.contains('p')).toBe(true)
// Check whether the content is correct
const contentText = wrapper.find('p').text();
expect(contentText).toBe("Aaron")
});
it('has tag', () = > {
// isEmpty(): Assert that the Wrapper contains no child nodes.
expect(wrapper.find("button").isEmpty()).toBeFalsy();
// exists(): Assert whether the Wrapper or WrapperArray exists.
expect(wrapper.findAll('img').exists()).toBeFalsy()
});
it('has className', () = > {
// attributes(): Return the attributes object of the Wrapper DOM node
expect(wrapper.find('p').attributes().class).toContain('outer');
// classes(): Return an array of the classes on the Wrapper DOM node
expect(wrapper.find('p').classes()).toContain('outer');
});
it('has style', () = > {
// hasStyle: Check for the corresponding inline style
expect(wrapper.find("p").hasStyle('padding-top', '10')).toBeTruthy()
});
});Routing Tests
Routing relies on the browser environment and cannot be used normally in unit tests. You need to use jest.mock to simulate a vue-router environment.
jest.mock("vue-router", () => {
const realModule = jest.requireActual("vue-router");
const mockRouter = {
...realModule,
currentRoute: {},
useRouter: () => ({
push(route: any) {
mockRouter.currentRoute.value = route;
},
currentRoute: mockRouter.currentRoute
})
};
return mockRouter;
});In the code above, the object returned by the function simulates a vue-router environment and changes the value of currentRoute when a push operation is triggered in that environment.
Scenario:
Suppose there are two route configurations, Home and About. The Home page has a button that navigates to the About page when clicked.
We can now write a unit test for this scenario. The code is as follows:
import Home from "@/pages/Home.vue";
import { useRouter } from 'vue-router';
test("Home.vue GoAbout", async () => {
const wrapper = mount(Home as any);
const oBtn1 = wrapper.find("#btn1");
await oBtn1.trigger("click");
const router = useRouter();
const routerName = router.currentRoute?.value?.name;
expect(routerName).toBe("About");
});Note that the argument passed to push in the code affects the final assertion result. In the example above, the production code calls push({ name: "About" }), so About is used as the expected result in the final assertion.
State Management Tests
There are many state management tools. This article uses pinia, which needs to be installed.
# npm
npm install pinia -S
# yarn
yarn add pinia -Spinia already includes a mock environment for unit testing, so we only need to perform some simple configuration.
import { setActivePinia, createPinia } from 'pinia';
beforeEach(() => {
setActivePinia(createPinia());
});Scenario:
Home contains a button that, when clicked, must change a value in pinia (fooValue). The new value is Zhang San.
We can now write a unit test for this scenario. The code is as follows:
import Home from "@/pages/Home.vue";
import { useHomeStore } from "@/store/module/Home";
test("Home.vue Change Pinia", () => {
const homeStore = useHomeStore();
const vm = mount(Home as any);
const oBtn = vm.find("#btn");
oBtn?.trigger("click");
expect(homeStore.fooValue).toBe("Aaron");
});Note that the corresponding store file must be imported here before you can read the updated value.
Data Request Tests
A common development requirement is to trigger a request or change a value when a particular button is clicked. This is also usually handled through mocking.
Scenario:
Home contains a button that must initiate an ajax request or an asynchronous operation when clicked. We need to verify whether the final value is the expected one.
We can now write a unit test for this scenario. The code is as follows:
import Home from "@/pages/Home.vue";
it('Home onGetAjax', (done) => {
const wrapper = mount(Home as any, {
setup() {
const data = ref({});
const onGetAjax = async () => {
data.value = mockData.data;
}
return { onGetAjax, data }
}
});
wrapper.find('#btn3').trigger('click');
wrapper.vm.$nextTick(async () => {
await wrapper.vm.onGetAjax();
expect(wrapper.vm.data).toEqual(mockData.data)
done();
});
});All data-processing operations need to be mocked in onGetAjax above. Of course, axios can also be used here to make a real data request. There is another way to handle this as well.
import Home from "@/pages/Home.vue";
// quantityBaseList: the final mock data
import { quantityBaseList } from "./quantityBase.mock";
const ajaxMock = (vai) => vai();
const getData = () => {
return new Promise((res) => {
res(quantityBaseList)
})
};
jest.mock("axios", () => {
const mAxiosInstance = {
get: jest.fn()
};
return {
create: jest.fn(() => mAxiosInstance),
};
});
// This is required here
// Mock the data-request function here
jest.mock('@/api/Home', () => {
return {
getCreateCustomerData: jest.fn(getData)
}
});
it("Home getTabeList", () => {
return wrapper.vm.$nextTick(async (res) => {
const result = await ajaxMock(getData);
expect(result.data.items).toEqual(quantityBaseList.data.items);
expect(result.data.totalCount).toEqual(quantityBaseList.data.totalCount);
});
});The code above directly mocks the method that requests data. You can also assert the subsequent operations required after the data request is complete.
Component Testing
With the unit testing environment successfully configured, the next and most important step is to test components. Since unit tests run in a node environment, in many cases we cannot directly test using elements of the actual development environment. These therefore often need to be mocked manually during unit testing.
Testing Component Props
We have discussed many page-related topics above. Besides pages, components also need to be tested. For components, props are probably the most common item to test.
Scenario:
A component needs to receive a prop, model<object>. We only need to test whether this model can be received properly.
let model = ref({
name: "张三"
});
it("provide/inject", () => {
let parent = mount(Detail as any, {
props: { model },
});
expect(child.vm.parentProps?.model).toEqual(model);
});Testing Custom Events
A custom event generally means notifying the parent level to perform some response after an event has finished executing inside a component. Custom events are frequently used in system development.
Scenario:
Home contains a Foo component. Foo has a button, and Home needs to execute a function when that button is clicked.
import Home from "@/pages/Home.vue";
import Foo from "@/components/Foo/index.vue";
describe('Test for Foo Component', () => {
wrapper = mount(Home as any);
it('addCounter Fn should be called', () = > {
const mockFn = jest.fn();
wrapper.setMethods({
'addCounter': mockFn
});
wrapper.find(Foo).vm.$emit('add', 100);
expect(mockFn).toHaveBeenCalledTimes(1);
});
wrapper.destroy()
});Here, the $on method replaces Home’s custom add event with a Mock function. A custom event cannot be triggered with trigger, because trigger is only for DOM events. Use $emit to trigger a custom event, after first locating the Foo component with find.
Testing Computed Properties
A computed property is a data value calculated from other data: the value of one variable needs to be derived from other variables. Computed properties have many uses.
Scenario:
The FooText component contains an input tag. A computed property reverses the value entered in the input and displays the result in a p tag in the component.
import FooText from "@/components/FooText/index.vue";
describe('Test for Foo Component', () => {
beforeEach(() => {
wrapper = shallow(FooText);
});
afterEach(() => {
wrapper.destroy()
});
it('test computed', () => {
// Use setProps to set props
wrapper.setProps({needReverse: false});
wrapper.vm.inputValue = 'ok';
expect(wrapper.vm.outputValue).toBe('ok');
});
});Testing Data Watchers
When a value changes, other operations may need to be performed. This is commonly used when encapsulating components: after external data changes, the component needs to adjust its internal state.
Scenario:
In the FooText component, watch monitors changes to the input’s value, and a function needs to execute after the value changes.
import FooText from "@/components/FooText/index.vue";
describe('Test watch', () = > {
let spy;
beforeEach(() = > {
wrapper = shallow(FooText);
spy = jest.spyOn(console, 'log');
});
afterEach(() = > {
wrapper.destroy();
spy.mockClear()
});
it('is called with the new value in other cases', () = > {
// Assigning a value to inputValue calls spy once, so the spy state needs to be cleared
// Clear the recorded state
spy.mockClear();
wrapper.vm.inputValue = 'ok';
return wrapper.vm.$nextTick(() = > {
expect(spy).not.toBeCalled();
});
});
};Dependency Injection Tests
Projects may use dependency injection through provide/inject. This generally involves nested parent and child components.
Scenario:
The two components are Detail and DetailItem. The Detail component passes model down through provide. We need to test whether the content DetailItem receives through inject is what the parent component passed in.
import Detail from "@/components/Detail/index.vue";
import DetailItem from "@/components/DetailItem/index.vue";
it("provide/inject", () => {
let parent = mount(Detail, {
props: { model },
slots: {
default: DetailItem
}
});
let child = parent.findComponent(DetailItem);
expect(child.vm.parentProps?.model).toEqual(model);
});Slot Tests
Testing slots is also essential. In particular, whether the parameters exposed by a slot are correct is sometimes a concern.
Scenario:
The DetailItem component can use a slot to render content. The slot exposes a value parameter for rendering. Test whether value is correct.
it("render slots", () => {
const wrapper = mount(DetailItem, {
global: {
provide: {
"detail": reactive({
model,
align: "left",
labelWidth: "100px"
})
},
},
slots: {
default: (item) => `<b>${item.value}</b>`
},
props: {
label,
prop,
align: "left",
labelWidth: "100px"
}
});
expect(`<b>${model.value[prop]}</b>`).toBe(wrapper.find(".w-full").text())
})Understanding and Using Test Reports
SonarQube is a code quality management tool that can check code quality, security, maintainability, and other aspects. It supports multiple programming languages and technology stacks and provides extensive metrics and reports to help development teams better manage and optimize code quality.
For front-end projects, SonarQube can use front-end test reports to evaluate code quality. First, configure a testing framework in the front-end project and generate test reports. Import the test reports into SonarQube so it can read and analyze them. SonarQube supports multiple test report formats, such as JUnit, Surefire, and Cobertura. Choose the corresponding SonarQube test report plugin for importing based on the report format generated by your front-end testing framework.
Configure checks and metrics for the front-end project in SonarQube, such as code coverage, code complexity, and code duplication. SonarQube generates corresponding code quality reports and metric analyses based on the test reports and checks. Development teams can use these reports and metrics to optimize and manage front-end code quality.
After the unit tests run, a folder named coverage is generated in the project root directory. The clover.xml and lcov.info files in this folder contain coverage-related information.
Add the following to the run command for sonar-project.properties:
// Location of the xml file
sonar.testExecutionReportPaths=test/covrage/test-report.xml
// Location of lcov.info
sonar.javascript.lcov.reportPaths=test/covrage/lcov.infoAfter Jest finishes running, it generates a coverage summary table. All files in the coverage statistics folder are checked. Coverage metrics:
File:File pathStatements: Statement coverage;execution of every statementBranches: Branchcoverage; execution of every if blockFunctions: Function coverage;calls to every function in the programLines: Linecoverage; execution of every line in the program
------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------------|---------|----------|---------|---------|-------------------
All files | 63.95 | 56.42 | 70.31 | 67.68 |
src/components | 68.84 | 65.11 | 67.85 | 73.8 |
Foo.vue | 67.91 | 65.11 | 66.66 | 73.17 |
------------------|---------|----------|---------|---------|-------------------Summary
Unit testing is an important way to improve software development quality. It helps companies improve product quality and customer satisfaction, laying a solid foundation for long-term business development. Through unit testing, companies can identify and resolve code problems promptly, improve code maintainability and extensibility, reduce the costs and risks of code maintenance, and provide a better foundation for future development. Unit testing can also boost developers’ confidence and motivation, encourage teamwork and innovation, and create more value and competitive advantages for the company.
When conducting unit tests, keep in mind that unit testing is not a simple task: it requires testers to have a certain level of technical skill and experience. Testers should give full consideration to test case coverage and the accuracy of test results to ensure effective, reliable testing. They also need to understand the project’s requirements and features and design tests and write test cases based on the actual circumstances to ensure comprehensive, complete testing.
In summary, unit testing is an indispensable part of software development. It can help companies improve software development quality and customer satisfaction, laying a solid foundation for long-term business development. Companies should therefore place great importance on unit testing, actively promote its principles, and continually improve their testing proficiency and technical capabilities to bring fresh momentum and vitality to future business development.

