import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { userEvent } from '@testing-library/user-event'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Mock } from 'vitest'; import { z } from 'zod/v4'; import { Form } from './Form.tsx'; describe('Form', () => { const testid = 'test-form'; const onError = vi.fn(); const onSubmit = vi.fn(); describe('conditional rendering', () => { beforeEach(() => { render(
); }); afterEach(() => { vi.clearAllMocks(); }); it('should render', () => { expect(screen.getByTestId(testid)).toBeInTheDocument(); }); it('should not allow submitting the form with a zod error', async () => { fireEvent.submit(screen.getByTestId(testid)); await waitFor(() => expect(screen.getAllByTestId('error-message-text').map((e) => e.innerHTML)).toMatchObject([ 'Please enter a number' ]) ); expect(onBeforeSubmit).not.toHaveBeenCalled(); expect(onSubmit).not.toHaveBeenCalled(); }); it('should not allow submitting the form with the onBeforeSubmit error', async () => { onBeforeSubmit.mockResolvedValueOnce({ errorMessage: 'Invalid!', success: false }); const field: HTMLInputElement = screen.getByLabelText('Value'); await userEvent.type(field, '-1'); fireEvent.submit(screen.getByTestId(testid)); await waitFor(() => expect(screen.getAllByTestId('error-message-text').map((e) => e.innerHTML)).toMatchObject(['Invalid!']) ); expect(onSubmit).not.toHaveBeenCalled(); }); it('should allow submitting the form if onBeforeSubmit returns true', async () => { onBeforeSubmit.mockResolvedValueOnce({ success: true }); const field: HTMLInputElement = screen.getByLabelText('Value'); await userEvent.type(field, '-1'); fireEvent.submit(screen.getByTestId(testid)); await waitFor(() => expect(onSubmit).toHaveBeenCalledOnce()); }); }); });