diff --git a/src/boot/dataCy.js b/src/boot/dataCy.js index 18f200ae6..d26012a60 100644 --- a/src/boot/dataCy.js +++ b/src/boot/dataCy.js @@ -2,16 +2,10 @@ export default { mounted: function (el, binding, { ctx }) { const { innerText, localName } = el; const { type, attrs } = ctx; - - el.setAttribute( - 'data-cy', - `${attrs?.label ?? innerText}_${type.name.replace('Q', '').toLowerCase()}` - ); - console.error('dataCy', el.getAttribute('data-cy')); - }, - unmounted: function (el) { - if (el._handleKeydown) { - window.removeEventListener('keydown', el._handleKeydown); - } + const name = ctx.parent.attrs?.name ?? ctx.parent.attrs?.label ?? innerText; + const value = `${attrs.dataCy ?? name}_${type.name + .replace('Q', '') + .toLowerCase()}`; + el.setAttribute('data-cy', value); }, }; diff --git a/test/vitest/__tests__/composables/dataCy.spec.js b/test/vitest/__tests__/composables/dataCy.spec.js new file mode 100644 index 000000000..8afa0a7e0 --- /dev/null +++ b/test/vitest/__tests__/composables/dataCy.spec.js @@ -0,0 +1,68 @@ +// tests/dataCy.spec.js +import { mount, shallowMount } from '@vue/test-utils'; +import { describe, it, expect } from 'vitest'; +import { Quasar, QInput, QSelect, QIcon, QBtn } from 'quasar'; +import dataCy from 'src/boot/dataCy.js'; +const mountWithQuasar = (component, options) => { + return mount(component, { + global: { + plugins: [Quasar], + stubs: { + vDataCy: true, + }, + directives: { + dataCy: dataCy, + }, + }, + ...options, + }); +}; + +describe('dataCy directive', () => { + it.only('applies data-cy attribute to QInput', () => { + const wrapper = mountWithQuasar(QInput, { + props: { + label: 'Test Input', + }, + }); + const input = wrapper.find('input'); + dataCy.mounted(input.element, null, { + ctx: { + type: QInput, + attrs: { dataCy: 'Test Input' }, + parent: { attrs: { label: 'Test Input' } }, + }, + }); + expect(input.attributes('data-cy')).toBe('Test Input_input'); + }); + + it('applies data-cy attribute to QSelect', () => { + const wrapper = mountWithQuasar(QSelect, { + props: { + label: 'Test Select', + }, + }); + const select = wrapper.find('.q-field__native'); + expect(select.attributes('data-cy')).toBe('Test Select_select'); + }); + + it('applies data-cy attribute to QIcon', () => { + const wrapper = mountWithQuasar(QIcon, { + props: { + name: 'home', + }, + }); + const icon = wrapper.find('i'); + expect(icon.attributes('data-cy')).toBe('home_icon'); + }); + + it('applies data-cy attribute to QBtn', () => { + const wrapper = mountWithQuasar(QBtn, { + props: { + label: 'Test Button', + }, + }); + const button = wrapper.find('button'); + expect(button.attributes('data-cy')).toBe('Test Button_btn'); + }); +});