# Vitest 組件測試練習 ![](https://i.imgur.com/8fS5fVr.png) [Test Util Vue 參考網址]([https://test-utils.vuejs.org/guide/](https://)) [Github專案原始碼](https://github.com/vince115/vueshool) ## 測試練習 1. Counter * 等值測試 ``` / expect(1).toBe(1) ``` * 點擊測試 emits an event when clicked ``` / const wrapper = mount(Counter) await wrapper.find('button').trigger('click') expect(wrapper.emitted()).toHaveProperty('increment') ``` 2. Input * 賦值測試 sets the value ``` / const wrapper = mount(Input) const input = wrapper.find('input') await input.setValue('my@mail.com') expect(input.element.value).toBe('my@mail.com') ``` * 點擊emits事件測試 emits an event when clicked ``` / const wrapper = mount(Input) await wrapper.find('button').trigger('click') expect(wrapper.emitted()).toHaveProperty('text-submit') ``` * 點擊emits事件測試 emits the input to its parent ``` / const wrapper = mount(Input) await wrapper.find('input').setValue('my@mail.com') await wrapper.find('button').trigger('click') expect(wrapper.find('label').text()).toBe('my@mail.com')· ``` * 問題: emitted('handleSubmit')[0][0] 無法接取value, 所以改由label text()去做toBe() ``` / //expect(wrapper.emitted('handleSubmit')[0][0]).toBe('my@mail.com') ``` 3. FromC * 問題: 導入元件失敗(form) ![](https://i.imgur.com/Z1looGY.png) ...卡很久,先跳過 4. Password * 賦值測試 sets the value ``` \ const wrapper = mount(Password) const input = wrapper.find('input') await input.setValue('Abcd123456') expect(input.element.value).toBe('Abcd123456') ``` * 賦值測試 sets the value ``` \ const wrapper = mount(Password, { props: { minLength: 10 }, data() { return { password: 'short' } } }) expect(wrapper.html()).toContain('Password must be at least 10 characters') ``` * 問題: * * error 的初始設定及判斷 * * password.length 初始值為undefined 與 minLength.value 來判斷大小,會有問題。 5. Show * 顯示測試 renders a greeting when show is true ``` \ const wrapper = mount(Show) expect(wrapper.html()).toContain('Hello') await wrapper.setProps({ show: false }) expect(wrapper.html()).not.toBe('Hello') // expect(wrapper.emitted()).toHaveProperty('text-submit') ```