diff --git a/packages/happy-dom/src/nodes/html-input-element/HTMLInputElement.ts b/packages/happy-dom/src/nodes/html-input-element/HTMLInputElement.ts index d74b9014a..fa2c71c25 100644 --- a/packages/happy-dom/src/nodes/html-input-element/HTMLInputElement.ts +++ b/packages/happy-dom/src/nodes/html-input-element/HTMLInputElement.ts @@ -774,9 +774,9 @@ export default class HTMLInputElement extends HTMLElement { * * @param value Value. */ - public set value(value: string) { + public set value(value: string | null) { // The value maybe not string, so we need to convert it to string - value = String(value); + value = value === null ? '' : String(value); switch (this.type) { case 'hidden': case 'submit': @@ -788,12 +788,13 @@ export default class HTMLInputElement extends HTMLElement { this.setAttribute('value', value); break; case 'file': - if (value !== '') { + if (value !== null && value !== '') { throw new this[PropertySymbol.window].DOMException( 'Input elements of type "file" may only programmatically set the value to empty string.', DOMExceptionNameEnum.invalidStateError ); } + this[PropertySymbol.files] = new FileList(); break; default: const oldValue = this.value; diff --git a/packages/happy-dom/test/nodes/html-input-element/HTMLInputElement.test.ts b/packages/happy-dom/test/nodes/html-input-element/HTMLInputElement.test.ts index 5a5483251..869aeefd2 100644 --- a/packages/happy-dom/test/nodes/html-input-element/HTMLInputElement.test.ts +++ b/packages/happy-dom/test/nodes/html-input-element/HTMLInputElement.test.ts @@ -78,6 +78,10 @@ describe('HTMLInputElement', () => { element.type = type; element.value = 'VALUE'; expect(element.getAttribute('value')).toBe('VALUE'); + element.value = null; + expect(element.getAttribute('value')).toBe(''); + element.value = (undefined); + expect(element.getAttribute('value')).toBe('undefined'); }); } @@ -91,8 +95,19 @@ describe('HTMLInputElement', () => { }); it('Accepts an empty string if type is "file".', () => { + const fileList = element.files; element.type = 'file'; element.value = ''; + expect(element.files).not.toBe(fileList); + expect(element.files.length).toBe(0); + }); + + it('Accepts null if type is "file".', () => { + const fileList = element.files; + element.type = 'file'; + element.value = null; + expect(element.files).not.toBe(fileList); + expect(element.files.length).toBe(0); }); it('Trims the value if type is "email".', () => { @@ -204,6 +219,15 @@ describe('HTMLInputElement', () => { element.value = ' \n\rhttp://www.test.com\n\r '; expect(element.value).toBe('http://www.test.com'); }); + + it('Converts null to empty string.', () => { + element.type = 'text'; + element.value = 'test'; + element.value = null; + expect(element.value).toBe(''); + element.value = (undefined); + expect(element.value).toBe('undefined'); + }); }); describe('get valueAsNumber()', () => {