@@ -138,6 +138,80 @@ describe('AutocompleteController', () => {
138
138
expect ( fetchMock . requests ( ) [ 1 ] . url ) . toEqual ( '/path/to/autocomplete?query=foo' ) ;
139
139
} ) ;
140
140
141
+ it ( 'resets when ajax URL attribute on a select element changes' , async ( ) => {
142
+ const { container, tomSelect } = await startAutocompleteTest ( `
143
+ <label for="the-select">Items</label>
144
+ <select
145
+ id="the-select"
146
+ data-testid="main-element"
147
+ data-controller="autocomplete"
148
+ data-autocomplete-url-value="/path/to/autocomplete"
149
+ ></select>
150
+ ` ) ;
151
+
152
+ const selectElement = getByTestId ( container , 'main-element' ) as HTMLSelectElement ;
153
+
154
+ // initial Ajax request on focus
155
+ fetchMock . mockResponseOnce (
156
+ JSON . stringify ( {
157
+ results : [
158
+ {
159
+ value : 3 ,
160
+ text : 'salad' ,
161
+ } ,
162
+ ] ,
163
+ } )
164
+ ) ;
165
+
166
+ fetchMock . mockResponseOnce (
167
+ JSON . stringify ( {
168
+ results : [
169
+ {
170
+ value : 1 ,
171
+ text : 'pizza' ,
172
+ } ,
173
+ {
174
+ value : 2 ,
175
+ text : 'popcorn' ,
176
+ } ,
177
+ ] ,
178
+ } )
179
+ ) ;
180
+
181
+ const controlInput = tomSelect . control_input ;
182
+
183
+ // wait for the initial Ajax request to finish
184
+ userEvent . click ( controlInput ) ;
185
+ await waitFor ( ( ) => {
186
+ expect ( container . querySelectorAll ( '.option[data-selectable]' ) ) . toHaveLength ( 1 ) ;
187
+ } ) ;
188
+
189
+ controlInput . value = 'foo' ;
190
+ controlInput . dispatchEvent ( new Event ( 'input' ) ) ;
191
+
192
+ await waitFor ( ( ) => {
193
+ expect ( container . querySelectorAll ( '.option[data-selectable]' ) ) . toHaveLength ( 2 ) ;
194
+ } ) ;
195
+
196
+ expect ( selectElement . value ) . toBe ( '' ) ;
197
+ tomSelect . addItem ( '2' ) ;
198
+ expect ( selectElement . value ) . toBe ( '2' ) ;
199
+
200
+ selectElement . outerHTML = `
201
+ <select
202
+ id="the-select"
203
+ data-testid="main-element"
204
+ data-controller="autocomplete"
205
+ data-autocomplete-url-value="/path/to/autocomplete2"
206
+ ></select>
207
+ ` ;
208
+
209
+ // wait for the MutationObserver to flush these changes
210
+ await shortDelay ( 10 ) ;
211
+
212
+ expect ( selectElement . value ) . toBe ( '' ) ;
213
+ } ) ;
214
+
141
215
it ( 'connect with ajax URL on an input element' , async ( ) => {
142
216
const { container, tomSelect } = await startAutocompleteTest ( `
143
217
<label for="the-input">Items</label>
0 commit comments