import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils' import { afterEach, describe, expect, it, vi } from 'vitest' import CardConverter from './CardConverter.vue' enableAutoUnmount(afterEach) afterEach(() => { vi.unstubAllGlobals() }) function getAlert() { const alert = document.body.querySelector('[role="alert"]') if (!alert) { throw new Error('Expected an alert to be rendered') } return alert } describe('CardConverter', () => { it('shows client validation without calling the API', async () => { const fetchMock = vi.fn() vi.stubGlobal('fetch', fetchMock) const wrapper = mount(CardConverter, { props: { apiBaseUrl: 'http://127.0.0.1:8080' }, }) await wrapper.get('input').setValue('۱۲۳') await wrapper.get('form').trigger('submit') expect(fetchMock).not.toHaveBeenCalled() expect(getAlert().textContent).toContain('۱۶ رقم') }) it('renders the returned iban after a successful request', async () => { vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue( new Response( JSON.stringify({ data: { iban: 'IR820540102680020817909002' }, requestId: 'request-test', }), { status: 200, headers: { 'Content-Type': 'application/json' } }, ), ), ) const wrapper = mount(CardConverter, { props: { apiBaseUrl: 'http://127.0.0.1:8080' }, attachTo: document.body, }) await wrapper.get('input').setValue('۶۰۳۷ ۹۹۷۵ ۱۲۳۴ ۵۶۷۸') await wrapper.get('form').trigger('submit') await flushPromises() expect(wrapper.text()).toContain('IR82 0540 1026 8002 0817 9090 02') expect(document.activeElement?.getAttribute('data-result')).toBe('iban') }) it('renders the safe API error message', async () => { vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue( new Response( JSON.stringify({ error: { code: 'conversion_rejected', message: 'تبدیل این شماره کارت انجام نشد.', }, requestId: 'request-test', }), { status: 422, headers: { 'Content-Type': 'application/json' } }, ), ), ) const wrapper = mount(CardConverter, { props: { apiBaseUrl: 'http://127.0.0.1:8080' }, }) await wrapper.get('input').setValue('6037997512345678') await wrapper.get('form').trigger('submit') await flushPromises() expect(getAlert().textContent).toContain('تبدیل این شماره کارت انجام نشد.') }) })