1. Getting started with simple use cases
Vue
Provided@vue/test-utils
Let's help us perform unit testing and createVue
When 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); }); });
shallowMount
Will return onewrapper
,thiswrapper
The 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,Vue
Configure jest in, refer to:/zh/guides/#…
Then add onescript
The 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!