preface
Before we get started, let’s talk about what automated testing is. Typically, after the requirements are identified, the test writes test cases and then executes the tests step by step according to the procedures described in the test cases to get a comparison of the actual results with the expected results. In this process, in order to save manpower, time or hardware resources, improve the efficiency of testing, it introduced the concept of automated testing.
So now that you know what automated testing is, let’s look at how the front end implements automated testing. There are two common scenarios for implementing front-end automated testing
- Unit-test: a white-box test of a corresponding test. Execute the code in the test framework and give the expected output, then compare the actual output to the expected output. To determine whether or not they passed the test.
- E2e-test (end-to-end test) : black box test in the corresponding test. After the project starts, the test framework simulates the user’s actions, such as clicking, typing, and so on. Then observe whether the elements on the page appear as expected. To determine whether or not they passed the test.
Today, I’m going to show you how to implement unit testing using JEST in vUE projects
Integrated Jest
A new project created using VUE-CLI can directly select JEST as the test framework. If it is an existing VUe-CLI project, you can use the following command to integrate JEST
vue add unit-jest
Copy the code
Jest configuration file
After integrating Jest, a Jest.config.js file is generated in the root directory. And configured @vue/cli-plugin-unit-jest, this default. The default configuration is as follows.
module.exports = {
moduleFileExtensions: [
"js"."jsx"."json".// tell Jest to handle *.vue files
"vue"].transform: {
// process *.vue files with vue-jest
"^.+\\.vue$": require.resolve("vue-jest"),
".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": require.resolve(
"jest-transform-stub"
),
"^.+\\.jsx? $": require.resolve("babel-jest")},transformIgnorePatterns: ["/node_modules/"].// support the same @ -> src alias mapping in source code
moduleNameMapper: {
"^ @ / (. *) $": "<rootDir>/src/$1"
},
testEnvironment: "jest-environment-jsdom-fifteen".// serializer for snapshots
snapshotSerializers: ["jest-serializer-vue"].testMatch: ["**/tests/unit/**/*.spec.[jt]s? (x)"."**/__tests__/*.[jt]s? (x)"].// https://github.com/facebook/jest/issues/6766
testURL: "http://localhost/".watchPlugins: [
require.resolve("jest-watch-typeahead/filename"),
require.resolve("jest-watch-typeahead/testname")]};Copy the code
However, this preset may not meet your needs, we need to extend it a little bit. Because we use files with the.js suffix in our project. We also use aliases other than @, so we need to add these two configurations to jest.config.js
module.exports = {
preset: "@vue/cli-plugin-unit-jest".transform: {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest"
},
moduleNameMapper: {
"^@api/(.*)$": "<rootDir>/src/server/api/$1"."^@views/(.*)$": "<rootDir>/src/views/$1"."^@com/(.*)$": "<rootDir>/src/components/$1"."^@store/(.*)$": "<rootDir>/src/store/$1"}};Copy the code
debugging
Debug based on vscode and configure in package.json
"test:debugger": "node --inspect-brk ./node_modules/@vue/cli-service/bin/vue-cli-service.js test:unit --runInBand --watch"
Copy the code
Then configure it in the.vscode\launch.json file
{
"version": "0.2.0"."configurations": [{"type": "node"."request": "attach"."name": "Attach to ws"."address": "localhost"."port": 9229."skipFiles": ["<node_internals>/**"]]}}Copy the code
After executing the above command, you can realize breakpoint debugging and listen for file changes to automatically refresh.
use
We call it “snapshots”, “triggers” and “expect-to”.
Here’s how these functions are used
The snapshot
The purpose of a snapshot is to preserve the complete DOM structure of the current component. The next time it executes, the updated DOM structure of the component is compared, and if the structure changes, the test case fails.
One note here is that I called await wrapper.vm.$nextTick(); After the mount method is executed, rendering of the component is an asynchronous process. So we need to call await wrapper.vm.$nextTick(); Then you can get the DOM structure of the component after rendering.
import { mount } from "@vue/test-utils";
import TestSnapshots from "@/components/TestSnapshots.vue";
describe("TestSnapshots.vue", () => {
it("render TestSnapshots".async() = > {const wrapper = mount(TestSnapshots);
await wrapper.vm.$nextTick();
expect(wrapper.html()).toMatchSnapshot();
});
});
Copy the code
Model events
Once a DOM node is found using the find method, you can use the trigger method to trigger events bound to that DOM node. Note here that trigger is asynchronous
import { mount } from "@vue/test-utils";
import TestTrigger from "@/components/TestTrigger.vue";
describe("TestTrigger.vue".async () => {
it("render TestTrigger".async() = > {const wrapper = mount(TestTrigger);
const btn = wrapper.find("button");
await closeBtn.trigger("click");
});
});
Copy the code
assertions
Get the object you want to judge, then execute the statement to test if the result is as expected. Here is a simple assertion judgment. Check whether the value of testData in the instantiated VUE instance meets the expectation
import { mount } from "@vue/test-utils";
import TestExpect from "@/components/TestExpect.vue";
describe("TestExpect.vue", () => {
it("render TestExpect", () = > {const wrapper = mount(TestExpect);
expect(wrapper.vm.testData).toBe(false); }); }); ! [](https://user-gold-cdn.xitu.io/2020/7/28/17394086692db12f? w=873&h=315&f=png&s=195213)
Copy the code
There are many other assertions that you can check out Jest’s official documentation
conclusion
Writing unit tests can make our code more robust. At the same time, strengthen our thinking of more business scenarios. This is just the most basic usage of JEST, but there are many more such as mock data, network interface testing, and so on. As the front end becomes more and more demanding, unit testing will become an essential skill for the front end.