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

Introduction
Delivering high-quality products to customers is one of a company’s core goals, and unit testing is an important means of achieving it. Unit testing can ensure that every part of a product has undergone rigorous testing, reducing the likelihood of defects and improving product reliability and stability. Unit test results can also provide customers with more accurate product quality reports, helping them better understand the product’s strengths and defects. In addition, unit testing can boost developers’ confidence and motivation, encourage teamwork and innovation, and help deliver better products and services to customers.
As front-end developers, however, our responsibility is not simply to complete development tasks. Before delivering a completed project, we must also ensure its quality. How to ensure the quality of delivery is a question well worth discussing. Most developers test their own work during development, but omissions or inadequate testing are inevitable and can lead to common bugs. Changes to a method or component may also affect other components that reference it. If those affected components are not tested, bugs can make their way into the delivered product.
Unit testing is therefore very necessary, yet its importance is often overlooked. Having unit tests is crucial for a complete project. This blog post will give you a fresh understanding of unit testing and also teach you how to set up an environment from scratch and use unit tests.
Why Write Unit Tests?
Necessity: JavaScript
lacks type checking, soerrors cannot be located during compilation. Unit tests can help you test various exceptional situations.Correctness: Tests can verify that code is correct, giving you confidence before deployment.
Automation: Although console
can print internalinformation, this is a one-time operation. The next test requires starting over, so efficiency cannot be guaranteed. By writing test cases, you can write once and run many times.Support for Refactoring: Products in the internet industry iterate rapidly, and iteration inevitably involves code refactoring. How can you ensure code quality after refactoring? With test cases to back you up, you can refactor confidently.
Unit Testing and End-to-End Testing
Most developers have probably heard more about Unit testing, commonly known as unit testing, but may be less familiar with E2E (end-to-end testing). What is the difference between the two?
Unit Testing
Unit testing tests from the programmer’s perspective. It views code as individual components so that each can be tested separately. Tests mainly check whether the execution result or return value of each function in a component matches the result asserted in the test.
End-to-End Testing
End-to-end testing (E2E) treats our program as a black box. I do not need to know how it works internally; I simply open a browser, enter the test content on the page, and see whether I get the expected result.
Unit tests let programmers easily test whether their logic returns the correct results after they have written it. E2E test code checks whether all requirements can be fulfilled correctly. Most importantly, after code has been refactored and substantial js changes have been made, the test code does not need to change when you need to test the requirements. You do not have to worry that refactoring will leave the product unable to meet the customer’s requirements.
Principles of Unit Testing
When writing unit tests, we need to mock components that depend on external systems or libraries, such as databases and network requests. This ensures that the unit under test is independent of the external environment and the states of other units, and that only the current unit’s functionality is tested. Components that depend on internal methods or classes can be tested directly, because those methods or classes are part of the current unit.
For the ComposeApi module, we should write independent unit tests using its real implementation, because it is called by other users. This helps ensure the code quality and maintainability of the ComposeApi module and ensures that it functions properly when used. For other modules that use ComposeApi, however, their dependency on it should be mocked when writing unit tests. This ensures that testing focuses only on the current module’s logic without being affected by other dependencies. It also ensures that the unit under test is independent of the external environment and the states of other units, and that only the current module’s functionality is tested.
Preparation
Before conducting unit tests, you need to choose a testing tool that suits your needs. This article uses Jest because it supports assertions and coverage testing and offers advantages such as simple syntax and powerful features. Jest can help us perform unit testing more effectively and improve code quality and reliability.
Before setting up the environment, we should understand the following concepts:
vite
typescript
vue3
Setting Up a Unit Testing Environment
We assume here that you already have a project to which you can add a testing environment. If not, create one yourself.
First, install the corresponding dependencies:
yarn add jest --dev
yarn add @types/jest --dev
yarn add babel-jest --dev
yarn add @babel/preset-env --dev
yarn add @vue/vue3-jest --dev
yarn add ts-jest --dev
yarn add @vue/cli-plugin-unit-jest --dev
yarn add @vue/test-utils@next --dev
yarn add @babel/preset-typescript --dev
yarn add babel-plugin-transform-vite-meta-env --dev
yarn add jest-environment-jsdom --dev
yarn add babel-plugin-transform-import-meta --devNote: yarn is used here to install dependencies. There is no need to dwell on the package manager; choose whichever one you prefer.
After the dependencies are installed, create a tests folder in the src directory to store test-related files.
Create jest.config.js in the root directory for the basic Jest initialization configuration:
module.exports = {
cache: false,
collectCoverage: true,
// babel presets
transform: {
"^.+\\.vue$": "@vue/vue3-jest", // Support importing Vue files
"^.+\\.jsx?$": "babel-jest", // Support import syntax
'^.+\\.tsx?$': 'ts-jest', // Support ts
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub' // Support importing css files
},
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'vue'],
// Path aliases
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
testEnvironment: 'jsdom',
testEnvironmentOptions: {
customExportConditions: ['node', 'node-addons'],
},
testMatch: [
'**/tests/**/*.test.[jt]s?(x)',
],
preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel'
};Since TypeScript is used here, tsconfig.json also needs to be adjusted so that the test files support TypeScript:
// Other configuration options are omitted; configure them according to your project requirements
{
"compilerOptions": {
// ...
"types": ["vite/client", "jest"] // Specify jest types
},
"include": [
// ...
"tests/**/*.ts" // Specify the unit test path
]
}Because Node cannot run TypeScript, babel is needed here to compile TypeScript. Configure babel by creating babel.config.js in the root directory:
module.exports = {
presets: [
[
"@babel/preset-env",
{
targets: {
node: "current"
}
}
]
],
plugins: [
'@babel/plugin-transform-arrow-functions',
'babel-plugin-transform-vite-meta-env',
['babel-plugin-transform-import-meta', { module: 'ES6' }]
],
};After configuring the environment, you can add a shortcut command under scripts in package.json to make the test command easier to run:
{
"scripts": {
// ...
"test": "jest"
},
}Common Assertions
toBe(): Testa specific valuetoEqual(): Testobject-type valuestoBeCalled(): Test whether afunction is calledtoHaveBeenCalledTimes(): Test how many times afunction is calledtoHaveBeenCalledWith(): Test the arguments passed whena function is calledtoBeNull(): The resultis nulltoBeUndefined(): The resultis undefinedtoBeDefined(): The resultis definedtoBeTruthy(): The resultis truetoBeFalsy(): The resultis falsetoContain(): Array matching; checkwhether an item is includedtoMatch(): Match stringpatterns; supports regular expressionstoBeCloseTo(): Floating-pointnumberstoThrow(): Supports strings,floating-point numbers, and variablestoMatchSnapshot(): Snapshot testingspecific to Jestnot.toBe(): Prepending .notgives the negated form
Creating Your First Unit Test
With the unit testing environment configured, you can now add a test file:
// test/index.test.ts
test("1+1=2", () => {
expect(1+1).toBe(2);
});After adding it, run the command:
yarn testYou will see the console output:
PASS tests/index.test.ts
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 0 | 0 | 0 | 0 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.798 s
Ran all test suites.
✨ Done in 5.32s.Front-end automated testing plays a crucial role in high-quality product delivery. By combining unit tests with end-to-end tests, we can detect problems in front-end code more comprehensively and fix them promptly, ensuring product stability and reliability. Setting up the basic environment is also a critical step: efficient testing is only possible in a stable environment.
This article has provided a thorough understanding of unit testing and explained how to write a simple unit test. We will follow up with unit testing for Vue. Stay tuned for “Penguin Geeks | Front-End Automated Testing: A Powerful Tool for High-Quality Product Delivery (Part 2).”

