|
| 1 | +import React from 'react'; |
| 2 | +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; |
| 3 | +import { Form } from '../Form'; |
| 4 | + |
| 5 | +const setInput = jest.fn(); |
| 6 | +const input = {}; |
| 7 | +const handleSubmit = jest.fn(); |
| 8 | + |
| 9 | +describe('Form', () => { |
| 10 | + beforeEach(() => { |
| 11 | + setInput.mockClear(); |
| 12 | + handleSubmit.mockClear(); |
| 13 | + }); |
| 14 | + |
| 15 | + it('renders a Form component with the correct elements', () => { |
| 16 | + const result = render( |
| 17 | + <Form setInput={setInput} input={input} handleSubmit={handleSubmit} /> |
| 18 | + ); |
| 19 | + expect(result.container).toBeDefined(); |
| 20 | + |
| 21 | + const form = screen.findByRole('form'); |
| 22 | + const buttons = screen.getAllByRole('button'); |
| 23 | + const textInput = screen.getByTestId('text-input'); |
| 24 | + const fileInput = screen.getByTestId('hidden-file-input'); |
| 25 | + |
| 26 | + expect(form).toBeDefined(); |
| 27 | + expect(buttons).toHaveLength(2); |
| 28 | + expect(textInput).toBeDefined(); |
| 29 | + expect(fileInput).toBeDefined(); |
| 30 | + }); |
| 31 | + |
| 32 | + it('can upload files to the input', async () => { |
| 33 | + const result = render( |
| 34 | + <Form setInput={setInput} input={input} handleSubmit={handleSubmit} /> |
| 35 | + ); |
| 36 | + expect(result.container).toBeDefined(); |
| 37 | + |
| 38 | + const fileInput: HTMLInputElement = screen.getByTestId('hidden-file-input'); |
| 39 | + const testFile = new File(['file content'], 'file.txt', { |
| 40 | + type: 'text/plain', |
| 41 | + }); |
| 42 | + File.prototype.text = jest.fn().mockResolvedValueOnce('foo.txt'); |
| 43 | + await waitFor(() => |
| 44 | + fireEvent.change(fileInput, { |
| 45 | + target: { files: [testFile] }, |
| 46 | + }) |
| 47 | + ); |
| 48 | + expect(setInput).toHaveBeenCalledTimes(1); |
| 49 | + expect(fileInput.files).not.toBeNull(); |
| 50 | + expect(fileInput.files![0]).toStrictEqual(testFile); |
| 51 | + }); |
| 52 | +}); |
0 commit comments