Unit testing

1. Test the correctness of the smallest unit of the program; 2, generally speaking, is to test a class or a method can work properly, and write test code;

case

demand

Unit test pages that increment from 0 by clicking the button

Counter.vue

< the template > < div > < h3 > count on the < / h3 > < p > {{count}} < / p > < button @ click ="increase"</button> </div> </template> <script>export default {
    data() {return{
            count:0
        }
    },
    methods:{
        increase(){
            this.count ++ ;
        }
    }
}
</script>
Copy the code

Unit test file counter.spec.js

import Vue from 'vue'
import {expect} from 'chai'
import {mount} from '@vue/test-utils'
import Counter from '@/components/Counter'
describe('test Counter. Vue',()=>{
    it('When I click the button, the value of count will be +1',()=>{
        const Constructor = Vue.extend(Counter);
        const vm = new Constructor().$mount(a); const button = vm.$el.querySelector('button');
        const clickE = new window.Event('click');
        button.dispatchEvent(clickE);
        vm._watcher.run();
        expect(Number(vm.$el.querySelector('span').textContent()).to.equal(1))
    })
})
describe('Test vue-test-util use case',()=>{
    it('Get the element and assert whether the values are consistent',()=>{
       const wrapper = mount(Counter);
       const h3= wrapper.find('h3');
       expect(h3.text().to.equal('the count on the'))})})Copy the code

Execute the following script from the command line to see whether the assertion succeeds or fails

npm run test