CodexBloom - Programming Q&A Platform

Testing a Custom Date Picker Component in Vue 3 with Jest and Vue Testing Library

πŸ‘€ Views: 65 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-07
vue jest testing-library JavaScript

I've searched everywhere and can't find a clear answer. I'm trying to write unit tests for a custom date picker component built with Vue 3 and using Jest along with Vue Testing Library. The component allows users to select a date and has a dropdown for months and a slider for years. Despite my efforts, the tests are failing on simulating user interactions and asserting the expected output. Here’s a simplified version of my date picker component: ```vue <template> <div> <select v-model="selectedMonth"> <option v-for="month in months" :key="month.value" :value="month.value">{{ month.name }}</option> </select> <input type="range" v-model="selectedYear" :min="minYear" :max="maxYear" /> <p>Selected Date: {{ formattedDate }}</p> </div> </template> <script> export default { data() { return { months: [ { name: 'January', value: 0 }, { name: 'February', value: 1 }, { name: 'March', value: 2 }, // ... other months ], selectedMonth: 0, selectedYear: 2023, minYear: 1900, maxYear: 2100, }; }, computed: { formattedDate() { return `${this.selectedYear}-${this.selectedMonth + 1}-01`; }, }, }; </script> ``` In my test file, I am trying to simulate changing the month and year inputs like so: ```javascript import { render, fireEvent } from '@testing-library/vue'; import DatePicker from '@/components/DatePicker.vue'; test('changes selected month and year', async () => { const { getByText, getByRole } = render(DatePicker); const select = getByRole('combobox'); await fireEvent.update(select, '1'); // Simulating selecting February const slider = getByRole('slider'); await fireEvent.update(slider, 2025); expect(getByText('Selected Date: 2025-2-01')).toBeInTheDocument(); }); ``` However, I am working with the following behavior message: ``` TypeError: want to read properties of undefined (reading 'formattedDate') ``` This happens because my test fails to properly update the `selectedMonth` and `selectedYear`. I've tried adjusting the way I target the select and slider elements, but nothing seems to work. I also ensured that I have the latest versions of Vue 3, Jest, and Vue Testing Library. Does anyone have insights on why this might be happening or how I can properly simulate these changes? Any help would be appreciated! I'm working on a API that needs to handle this. What am I doing wrong? What am I doing wrong?