import { beforeEach, describe, expect, it, vi } from 'vitest' import { flushPromises } from '@vue/test-utils' import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime' import LoginForm from '~/components/LoginForm.vue' const { api, navigateToMock } = vi.hoisted(() => ({ api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() }, navigateToMock: vi.fn() })) mockNuxtImport('useApi', () => () => api) mockNuxtImport('navigateTo', () => navigateToMock) describe('LoginForm', () => { beforeEach(() => { api.post.mockReset() navigateToMock.mockReset() useCookie('authenticated').value = false }) it('disables the login button until a password is entered', async () => { const wrapper = await mountSuspended(LoginForm) const button = wrapper.find('button[type="submit"]') expect(button.attributes('disabled')).toBeDefined() await wrapper.find('input').setValue('secret') expect(button.attributes('disabled')).toBeUndefined() }) it('logs in with the password, sets the cookie and goes home', async () => { api.post.mockResolvedValue({ success: true, data: true }) const wrapper = await mountSuspended(LoginForm) await wrapper.find('input').setValue('pa"ss') await wrapper.find('form').trigger('submit') await flushPromises() expect(api.post).toHaveBeenCalledWith('/api/Authentication/login', 'pa"ss') expect(useCookie('authenticated').value).toBe(true) expect(navigateToMock).toHaveBeenCalledWith('/') }) it('shows the error and stays on the page when the login fails', async () => { api.post.mockResolvedValue({ success: false, error: 'Incorrect password.' }) const wrapper = await mountSuspended(LoginForm) await wrapper.find('input').setValue('wrong') await wrapper.find('form').trigger('submit') await flushPromises() expect(wrapper.text()).toContain('Incorrect password.') expect(useCookie('authenticated').value).toBe(false) expect(navigateToMock).not.toHaveBeenCalled() }) it('can reveal and hide the password', async () => { const wrapper = await mountSuspended(LoginForm) const input = wrapper.find('input') expect(input.attributes('type')).toBe('password') await wrapper.find('button[aria-label="Show password"]').trigger('click') expect(input.attributes('type')).toBe('text') await wrapper.find('button[aria-label="Hide password"]').trigger('click') expect(input.attributes('type')).toBe('password') }) })