import { inputDuplicatorCreator } from '../input-duplicator'; import { assertNotNull } from '../utils/assert'; import { $, $$, removeEl } from '../utils/dom'; import { fireEvent } from '@testing-library/dom'; describe('Input duplicator functionality', () => { beforeEach(() => { document.documentElement.insertAdjacentHTML( 'beforeend', `
3
`, ); }); afterEach(() => { removeEl($$('form')); }); function runCreator() { inputDuplicatorCreator({ addButtonSelector: '.js-add-input', fieldSelector: '.js-input-source', maxInputCountSelector: '.js-max-input-count', removeButtonSelector: '.js-remove-input', }); } it('should ignore forms without a duplicator button', () => { removeEl($$('button')); expect(runCreator()).toBeUndefined(); }); it('should duplicate the input elements', () => { runCreator(); expect($$('input')).toHaveLength(1); fireEvent.click(assertNotNull($('.js-add-input'))); expect($$('input')).toHaveLength(2); }); it('should duplicate the input elements when the button is before the inputs', () => { const form = assertNotNull($('form')); const buttonDiv = assertNotNull($('.js-button-container')); removeEl(buttonDiv); form.insertAdjacentElement('afterbegin', buttonDiv); runCreator(); fireEvent.click(assertNotNull($('.js-add-input'))); expect($$('input')).toHaveLength(2); }); it('should not create more input elements than the limit', () => { runCreator(); for (let i = 0; i < 5; i += 1) { fireEvent.click(assertNotNull($('.js-add-input'))); } expect($$('input')).toHaveLength(3); }); it('should remove duplicated input elements', () => { runCreator(); fireEvent.click(assertNotNull($('.js-add-input'))); fireEvent.click(assertNotNull($('.js-remove-input'))); expect($$('input')).toHaveLength(1); }); it('should not remove the last input element', () => { runCreator(); fireEvent.click(assertNotNull($('.js-remove-input'))); fireEvent.click(assertNotNull($('.js-remove-input'))); for (let i = 0; i < 5; i += 1) { fireEvent.click(assertNotNull($('.js-remove-input'))); } expect($$('input')).toHaveLength(1); }); });