Performance: Testing props and events
This concept affects the speed and responsiveness of component updates and event handling in Vue applications.
import { mount } from '@vue/test-utils' import MyComponent from './MyComponent.vue' test('good: updates props without remounting', async () => { const wrapper = mount(MyComponent, { props: { count: 0 } }) await wrapper.setProps({ count: 1 }) expect(wrapper.text()).toContain('1') await wrapper.setProps({ count: 2 }) expect(wrapper.text()).toContain('2') })
import { mount } from '@vue/test-utils' import MyComponent from './MyComponent.vue' test('bad: tests props by remounting component repeatedly', () => { const wrapper = mount(MyComponent, { props: { count: 0 } }) wrapper.setProps({ count: 1 }) expect(wrapper.text()).toContain('1') wrapper.unmount() const wrapper2 = mount(MyComponent, { props: { count: 2 } }) expect(wrapper2.text()).toContain('2') })
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Remounting component for each prop change | Multiple mounts/unmounts | Multiple reflows | High paint cost | [X] Bad |
| Updating props on mounted component | Single mount, prop updates | Minimal reflows | Low paint cost | [OK] Good |
| Remounting component after event emit | Multiple mounts/unmounts | Multiple reflows | High paint cost | [X] Bad |
| Emitting event on mounted component | Single mount, event emit | No reflows | Minimal paint cost | [OK] Good |
emitted() returns an object of events emitted by the component.trigger() simulates DOM events, props() reads props, and setData() changes component data.const wrapper = mount(MyButton, { props: { label: 'Click' } })
await wrapper.find('button').trigger('click')
const events = wrapper.emitted()events contain if MyButton emits a 'click' event on button click?const wrapper = mount(MyInput, { props: { value: 'test' } })
wrapper.find('input').trigger('input', { target: { value: 'new' } })
expect(wrapper.emitted('input')[0]).toEqual(['new'])Pass the test and this pattern moves unknown