一、環境配置
1、安裝依賴
vue add @vue/cli-plugin-unit-jest
確保已經安裝了vue-cli3或vue-cli4,可以通過vue --version測試
安裝完成,時間略微長一點,5-10分鍾
安裝完成后package.json里會增加這些依賴
文件根目錄多出一個jest.config.js文件以及tests/unit/example.spec.js
依賴安裝完成后需要npm install
2、修改測試案例
修改tests文件夾下的unit文件夾下的example.spec.js中的代碼
1 import { mount } from '@vue/test-utils' 2 import HelloWorld from '@/testComponents/HelloWorld.vue' 3 4 describe('HelloWorld.vue', () => { 5 const wrapper = mount(HelloWorld); 6 const vm = wrapper.vm; 7 it('渲染', () => { 8 expect(wrapper.html()).toContain('<span>0</span>') 9 }) 10 it('計數器在點擊按鈕時自增', () => { 11 // 點擊之前 12 console.log('計數器點擊之前的值:' + vm.count); 13 // 調用實例中的increment方法,點擊計數器 14 vm.increment(); 15 // 點擊之后 16 console.log('計數器點擊之后的值:' + vm.count); 17 // 判斷最后的count是否為最后對應的值 18 expect(vm.count).toBe(1); 19 }) 20 })
修改HelloWorld.vue中的代碼
1 <template> 2 <div> 3 <span>{{ count }}</span> 4 <button @click="increment">自增</button> 5 </div> 6 </template> 7 <script> 8 export default { 9 data () { 10 return { 11 count: 0 12 } 13 }, 14 methods: { 15 increment () { 16 this.count++ 17 } 18 } 19 } 20 </script>
3、運行
npm run test:unit
運行結果
單獨運行一個測試用例:
npm run test:unit <name>
例如:npm run test:unit example