javascript / beginner
Snippet
Asserting Initial Counter Text with Vue Test Utils
Unit testing components ensures that rendering and data contracts behave predictably. Using Vue Test Utils mount function with Vitest, you can instantiate a component with specific props, locate targeted DOM elements using test attributes, and assert their text content accurately.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { mount } from '@vue/test-utils';import { describe, it, expect } from 'vitest';import CounterDisplay from './CounterDisplay.vue';describe('CounterDisplay.vue', () => {it('renders the initial count passed via props', () => {const wrapper = mount(CounterDisplay, {props: {initialCount: 5}});const countSpan = wrapper.find('[data-test="count-value"]');expect(countSpan.exists()).toBe(true);expect(countSpan.text()).toBe('5');});});
vue
Breakdown
1
import { mount } from '@vue/test-utils';
Imports the mount helper to render and mount a Vue component in an isolated test environment.
2
const wrapper = mount(CounterDisplay, { props: { initialCount: 5 } });
Mounts the target component while supplying a mock initialCount prop.
3
const countSpan = wrapper.find('[data-test="count-value"]');
Queries the rendered DOM tree for a specific element using a resilient data-test selector.
4
expect(countSpan.exists()).toBe(true);
Verifies that the requested DOM element was successfully rendered in the markup.
5
expect(countSpan.text()).toBe('5');
Asserts that the text content of the element matches the expected string representation.