diff --git a/src/cdk/testing/testbed/unit-test-element.ts b/src/cdk/testing/testbed/unit-test-element.ts index 1a281464dc40..5e743ab6d373 100644 --- a/src/cdk/testing/testbed/unit-test-element.ts +++ b/src/cdk/testing/testbed/unit-test-element.ts @@ -244,17 +244,20 @@ export class UnitTestElement implements TestElement { const options = this.element.querySelectorAll('option'); const indexes = new Set(optionIndexes); // Convert to a set to remove duplicates. - for (let i = 0; i < options.length; i++) { - const option = options[i]; - const wasSelected = option.selected; - - // We have to go through `option.selected`, because `HTMLSelectElement.value` doesn't - // allow for multiple options to be selected, even in `multiple` mode. - option.selected = indexes.has(i); + if (options.length && indexes.size) { + // Reset the value so all the selected states are cleared. + for (let i = 0; i < options.length; i++) { + options[i].selected = false; + } - if (option.selected !== wasSelected) { - hasChanged = true; - dispatchFakeEvent(this.element, 'change', true); + for (let i = 0; i < options.length; i++) { + if (indexes.has(i)) { + // We have to go through `option.selected`, because `HTMLSelectElement.value` doesn't + // allow for multiple options to be selected, even in `multiple` mode. + options[i].selected = true; + hasChanged = true; + dispatchFakeEvent(this.element, 'change', true); + } } } diff --git a/src/material/input/testing/native-select-harness.spec.ts b/src/material/input/testing/native-select-harness.spec.ts index 3fc7eb1569ba..695d9815b1ce 100644 --- a/src/material/input/testing/native-select-harness.spec.ts +++ b/src/material/input/testing/native-select-harness.spec.ts @@ -193,7 +193,7 @@ describe('MatNativeSelectHarness', () => { @Component({ template: ` - + Favorite food