Line 0
Link Here
|
0 |
- |
1 |
// Select2Helpers.js - Reusable Cypress functions for Select2 dropdowns |
|
|
2 |
|
3 |
/** |
4 |
* Helper functions for interacting with Select2 dropdown components in Cypress tests |
5 |
* Supports AJAX-based Select2s, triggering all standard Select2 events, and |
6 |
* multiple selection methods including index and text matching (partial/full) |
7 |
* |
8 |
* CHAINABILITY: |
9 |
* All Select2 helper commands are fully chainable. You can: |
10 |
* - Chain multiple Select2 operations (search, then select) |
11 |
* - Chain Select2 commands with standard Cypress commands |
12 |
* - Split complex interactions into multiple steps for better reliability |
13 |
* |
14 |
* Examples: |
15 |
* cy.get('#mySelect') |
16 |
* .select2({ search: 'foo' }) |
17 |
* .select2({ select: 'FooBar' }); |
18 |
* |
19 |
* cy.get('#mySelect') |
20 |
* .select2({ search: 'bar' }) |
21 |
* .select2({ selectIndex: 0 }) |
22 |
* .should('have.value', 'bar_value'); |
23 |
*/ |
24 |
|
25 |
/** |
26 |
* Main Select2 interaction command to perform operations on Select2 dropdowns |
27 |
* @param {string|JQuery} [subject] - Optional jQuery element (when used with .select2()) |
28 |
* @param {Object} options - Configuration options for the Select2 operation |
29 |
* @param {string} [options.search] - Search text to enter in the search box |
30 |
* @param {string|Object} [options.select] - Text to select or object with matcher options |
31 |
* @param {number} [options.selectIndex] - Index of the option to select (0-based) |
32 |
* @param {string} [options.selector] - CSS selector to find the select element (when not using subject) |
33 |
* @param {boolean} [options.clearSelection=false] - Whether to clear the current selection first |
34 |
* @param {Function} [options.matcher] - Custom matcher function for complex option selection |
35 |
* @param {number} [options.timeout=10000] - Timeout for AJAX responses in milliseconds |
36 |
* @param {boolean} [options.multiple=false] - Whether the select2 allows multiple selections |
37 |
* @param {number} [options.minSearchLength=3] - Minimum length of search text needed for Ajax select2 |
38 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
39 |
* |
40 |
* @example |
41 |
* // Basic usage |
42 |
* cy.get('#mySelect').select2({ search: 'foo', select: 'FooBar' }); |
43 |
* |
44 |
* @example |
45 |
* // Chained operations (more reliable, especially for AJAX Select2) |
46 |
* cy.get('#mySelect') |
47 |
* .select2({ search: 'foo' }) |
48 |
* .select2({ select: 'FooBar' }); |
49 |
* |
50 |
* @example |
51 |
* // With custom matcher |
52 |
* cy.get('#mySelect').select2({ |
53 |
* search: 'special', |
54 |
* matcher: (option) => option.text.includes('Special Edition') |
55 |
* }); |
56 |
*/ |
57 |
Cypress.Commands.add( |
58 |
"select2", |
59 |
{ |
60 |
prevSubject: "optional", |
61 |
}, |
62 |
(subject, options) => { |
63 |
// Default configuration |
64 |
const defaults = { |
65 |
search: null, |
66 |
select: null, |
67 |
selectIndex: null, |
68 |
selector: null, |
69 |
clearSelection: false, |
70 |
matcher: null, |
71 |
timeout: 10000, |
72 |
multiple: false, |
73 |
minSearchLength: 3, |
74 |
}; |
75 |
|
76 |
// Merge passed options with defaults |
77 |
const config = { ...defaults, ...options }; |
78 |
|
79 |
// Handle selecting the target Select2 element |
80 |
let $originalSelect; |
81 |
if (subject) { |
82 |
$originalSelect = subject; |
83 |
// Store the element ID as a data attribute for chaining |
84 |
cy.wrap(subject).then($el => { |
85 |
const selectId = $el.attr("id"); |
86 |
if (selectId) { |
87 |
Cypress.$($el).attr("data-select2-helper-id", selectId); |
88 |
} |
89 |
}); |
90 |
} else if (config.selector) { |
91 |
$originalSelect = cy.get(config.selector); |
92 |
} else { |
93 |
throw new Error( |
94 |
"Either provide a subject or a selector to identify the Select2 element" |
95 |
); |
96 |
} |
97 |
|
98 |
return cy.wrap($originalSelect).then($el => { |
99 |
const selectId = $el.attr("id") || $el.data("select2-helper-id"); |
100 |
|
101 |
if (!selectId) { |
102 |
throw new Error( |
103 |
"Select element must have an ID attribute for the Select2 helper to work correctly" |
104 |
); |
105 |
} |
106 |
|
107 |
// Handle clearing the selection if requested |
108 |
if (config.clearSelection) { |
109 |
cy.window().then(win => { |
110 |
win.$(`select#${selectId}`).val(null).trigger("change"); |
111 |
}); |
112 |
|
113 |
if ( |
114 |
config.search === null && |
115 |
config.select === null && |
116 |
config.selectIndex === null && |
117 |
config.matcher === null |
118 |
) { |
119 |
return cy.get(`select#${selectId}`); |
120 |
} |
121 |
} |
122 |
|
123 |
// Find the Select2 container and click to open dropdown |
124 |
cy.get(`select#${selectId}`) |
125 |
.siblings(".select2-container") |
126 |
.first() |
127 |
.find(".select2-selection") |
128 |
.first() |
129 |
.click({ force: true }); |
130 |
|
131 |
// Handle search functionality |
132 |
if (config.search !== null) { |
133 |
// Wait for search field to appear and type search text |
134 |
cy.get(".select2-search--dropdown .select2-search__field") |
135 |
.first() |
136 |
.should("be.visible") |
137 |
.type(config.search, { force: true }); |
138 |
|
139 |
// Check minimum search length requirements |
140 |
if (config.search.length < config.minSearchLength) { |
141 |
cy.log( |
142 |
`Warning: Search text "${config.search}" may be too short for Ajax select2 (minimum typically ${config.minSearchLength} characters)` |
143 |
); |
144 |
} |
145 |
|
146 |
// Wait for results container to exist |
147 |
cy.get(".select2-results__options", { |
148 |
timeout: config.timeout, |
149 |
}).should("exist"); |
150 |
|
151 |
// Wait for options to be loaded and not in loading state |
152 |
cy.get(".select2-results__option", { |
153 |
timeout: config.timeout, |
154 |
}).should($options => { |
155 |
// Must have at least one option |
156 |
expect($options).to.have.length.at.least(1); |
157 |
|
158 |
const firstOptionText = $options |
159 |
.first() |
160 |
.text() |
161 |
.toLowerCase(); |
162 |
|
163 |
// Should not be in loading states |
164 |
expect(firstOptionText).to.not.include("searching"); |
165 |
expect(firstOptionText).to.not.include("loading"); |
166 |
expect(firstOptionText).to.not.include("please wait"); |
167 |
|
168 |
// Log if no results found, but don't fail here |
169 |
if ( |
170 |
firstOptionText.includes("no results") || |
171 |
firstOptionText.includes("please enter") |
172 |
) { |
173 |
cy.log( |
174 |
`Warning: No results found for search: "${config.search}"` |
175 |
); |
176 |
} |
177 |
}); |
178 |
} |
179 |
|
180 |
// Handle selection based on the provided options |
181 |
if ( |
182 |
config.select !== null || |
183 |
config.selectIndex !== null || |
184 |
config.matcher !== null |
185 |
) { |
186 |
// Wait for valid selectable options to be available and store matching logic |
187 |
cy.get(".select2-results__option") |
188 |
.should($options => { |
189 |
expect($options).to.have.length.at.least(1); |
190 |
|
191 |
const firstOptionText = $options |
192 |
.first() |
193 |
.text() |
194 |
.toLowerCase(); |
195 |
|
196 |
// Should not be in loading or error states for selection |
197 |
expect(firstOptionText).to.not.include("searching"); |
198 |
expect(firstOptionText).to.not.include("loading"); |
199 |
expect(firstOptionText).to.not.include("please wait"); |
200 |
expect(firstOptionText.length).to.be.greaterThan(0); |
201 |
|
202 |
// Should have selectable options (not just error messages) |
203 |
if ( |
204 |
firstOptionText.includes("no results") || |
205 |
firstOptionText.includes("please enter") |
206 |
) { |
207 |
throw new Error( |
208 |
`No selectable options found for search: "${config.search}"` |
209 |
); |
210 |
} |
211 |
|
212 |
// Perform selection logic and store the result for later use |
213 |
let optionIndex = -1; |
214 |
|
215 |
// Select by index |
216 |
if (config.selectIndex !== null) { |
217 |
expect(config.selectIndex).to.be.at.least(0); |
218 |
expect(config.selectIndex).to.be.below( |
219 |
$options.length |
220 |
); |
221 |
optionIndex = config.selectIndex; |
222 |
} |
223 |
// Select by custom matcher function |
224 |
else if ( |
225 |
config.matcher !== null && |
226 |
typeof config.matcher === "function" |
227 |
) { |
228 |
for (let i = 0; i < $options.length; i++) { |
229 |
const $option = $options.eq(i); |
230 |
const optionContent = { |
231 |
text: $option.text().trim(), |
232 |
html: $option.html(), |
233 |
element: $option[0], |
234 |
}; |
235 |
|
236 |
if (config.matcher(optionContent, i)) { |
237 |
optionIndex = i; |
238 |
break; |
239 |
} |
240 |
} |
241 |
} |
242 |
// Select by text (default) |
243 |
else if (config.select !== null) { |
244 |
if (typeof config.select === "string") { |
245 |
const selectText = config.select; |
246 |
|
247 |
// Try exact match first |
248 |
for (let i = 0; i < $options.length; i++) { |
249 |
if ( |
250 |
Cypress.$($options[i]).text().trim() === |
251 |
selectText |
252 |
) { |
253 |
optionIndex = i; |
254 |
break; |
255 |
} |
256 |
} |
257 |
|
258 |
// Fall back to partial match if no exact match |
259 |
if (optionIndex === -1) { |
260 |
for (let i = 0; i < $options.length; i++) { |
261 |
if ( |
262 |
Cypress.$($options[i]) |
263 |
.text() |
264 |
.trim() |
265 |
.includes(selectText) |
266 |
) { |
267 |
optionIndex = i; |
268 |
break; |
269 |
} |
270 |
} |
271 |
} |
272 |
} |
273 |
// Handle object format for advanced matching |
274 |
else if (typeof config.select === "object") { |
275 |
const matchType = |
276 |
config.select.matchType || "partial"; |
277 |
const text = config.select.text; |
278 |
|
279 |
if (!text) { |
280 |
throw new Error( |
281 |
'When using object format for selection, "text" property is required' |
282 |
); |
283 |
} |
284 |
|
285 |
let matcher; |
286 |
switch (matchType) { |
287 |
case "exact": |
288 |
matcher = optText => optText === text; |
289 |
break; |
290 |
case "startsWith": |
291 |
matcher = optText => |
292 |
optText.startsWith(text); |
293 |
break; |
294 |
case "endsWith": |
295 |
matcher = optText => |
296 |
optText.endsWith(text); |
297 |
break; |
298 |
case "partial": |
299 |
default: |
300 |
matcher = optText => |
301 |
optText.includes(text); |
302 |
} |
303 |
|
304 |
for (let i = 0; i < $options.length; i++) { |
305 |
const optionText = Cypress.$($options[i]) |
306 |
.text() |
307 |
.trim(); |
308 |
if (matcher(optionText)) { |
309 |
optionIndex = i; |
310 |
break; |
311 |
} |
312 |
} |
313 |
} |
314 |
} |
315 |
|
316 |
// Ensure we found an option to select |
317 |
if (optionIndex === -1) { |
318 |
throw new Error( |
319 |
`Could not find any option matching the selection criteria. Search: "${config.search}", Select: "${config.select}"` |
320 |
); |
321 |
} |
322 |
|
323 |
// Store the determined index as a data attribute on the first option element |
324 |
// This survives the should() retry cycles and can be read by subsequent commands |
325 |
Cypress.$($options[0]).attr( |
326 |
"data-select2-target-index", |
327 |
optionIndex |
328 |
); |
329 |
|
330 |
// Return true to satisfy the should() assertion |
331 |
return true; |
332 |
}) |
333 |
.then($options => { |
334 |
// Retrieve the stored index from the data attribute |
335 |
const targetIndex = parseInt( |
336 |
Cypress.$($options[0]).attr( |
337 |
"data-select2-target-index" |
338 |
), |
339 |
10 |
340 |
); |
341 |
|
342 |
// Click the option at the determined index |
343 |
return cy |
344 |
.get(".select2-results__option") |
345 |
.eq(targetIndex) |
346 |
.click({ force: true }); |
347 |
}); |
348 |
|
349 |
// Verify the selection was applied |
350 |
// Wait for the dropdown to close first (indicates selection is processing) |
351 |
cy.get(".select2-dropdown").should("not.exist"); |
352 |
|
353 |
// Wait a moment for Select2 to trigger change events and update the DOM |
354 |
cy.wait(100); |
355 |
|
356 |
// Then verify the selection was applied to the underlying select element |
357 |
cy.get(`select#${selectId}`).should($el => { |
358 |
const value = $el.val(); |
359 |
|
360 |
// For multiple selects, value might be an array |
361 |
if (Array.isArray(value)) { |
362 |
expect(value).to.have.length.at.least(1); |
363 |
expect(value[0]).to.not.be.null; |
364 |
expect(value[0]).to.not.equal(""); |
365 |
} else { |
366 |
expect(value).to.not.be.null; |
367 |
expect(value).to.not.equal(""); |
368 |
} |
369 |
}); |
370 |
} |
371 |
|
372 |
// Return the original select element for chaining |
373 |
return cy.get(`select#${selectId}`); |
374 |
}); |
375 |
} |
376 |
); |
377 |
|
378 |
/** |
379 |
* Helper to clear a Select2 selection |
380 |
* Can be used as a standalone command or as part of a chain |
381 |
* |
382 |
* @param {string} selector - jQuery-like selector for the original select element |
383 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
384 |
* |
385 |
* @example |
386 |
* // Standalone usage |
387 |
* cy.clearSelect2('#tagSelect'); |
388 |
* |
389 |
* @example |
390 |
* // As part of a chain |
391 |
* cy.get('#tagSelect') |
392 |
* .select2({ select: 'Mystery' }) |
393 |
* .clearSelect2('#tagSelect') |
394 |
* .select2({ select: 'Fantasy' }); |
395 |
*/ |
396 |
Cypress.Commands.add("clearSelect2", selector => { |
397 |
return cy.get(selector).select2({ clearSelection: true }); |
398 |
}); |
399 |
|
400 |
/** |
401 |
* Helper to search in a Select2 dropdown without making a selection |
402 |
* Useful for testing search functionality or as part of a multi-step interaction |
403 |
* |
404 |
* @param {string} selector - jQuery-like selector for the original select element |
405 |
* @param {string} searchText - Text to search for |
406 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
407 |
* |
408 |
* @example |
409 |
* // Standalone usage to test search functionality |
410 |
* cy.searchSelect2('#authorSelect', 'Gaiman'); |
411 |
* |
412 |
* @example |
413 |
* // Chained with selection - more reliable for AJAX Select2s |
414 |
* cy.get('#publisherSelect') |
415 |
* .searchSelect2('#publisherSelect', "O'Reilly") |
416 |
* .select2({ selectIndex: 0 }); |
417 |
*/ |
418 |
Cypress.Commands.add("searchSelect2", (selector, searchText) => { |
419 |
return cy.get(selector).select2({ search: searchText }); |
420 |
}); |
421 |
|
422 |
/** |
423 |
* Helper to select an option in a Select2 dropdown by text |
424 |
* Combines search and select in one command, but can be less reliable for AJAX Select2s |
425 |
* |
426 |
* @param {string} selector - jQuery-like selector for the original select element |
427 |
* @param {string|Object} selectText - Text to select or object with matcher options |
428 |
* @param {string} [searchText=null] - Optional text to search for before selecting |
429 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
430 |
* |
431 |
* @example |
432 |
* // Basic usage |
433 |
* cy.selectFromSelect2('#authorSelect', 'J.R.R. Tolkien'); |
434 |
* |
435 |
* @example |
436 |
* // With search text |
437 |
* cy.selectFromSelect2('#publisherSelect', 'O\'Reilly Media', 'O\'Reilly'); |
438 |
* |
439 |
* @example |
440 |
* // Using advanced matching options |
441 |
* cy.selectFromSelect2('#bookSelect', |
442 |
* { text: 'The Hobbit', matchType: 'exact' }, |
443 |
* 'Hobbit' |
444 |
* ); |
445 |
* |
446 |
* @example |
447 |
* // Chainable with other Cypress commands |
448 |
* cy.selectFromSelect2('#categorySelect', 'Fiction') |
449 |
* .should('have.value', 'fiction') |
450 |
* .and('be.visible'); |
451 |
*/ |
452 |
Cypress.Commands.add( |
453 |
"selectFromSelect2", |
454 |
(selector, selectText, searchText = null) => { |
455 |
return cy.get(selector).select2({ |
456 |
search: searchText, |
457 |
select: selectText, |
458 |
}); |
459 |
} |
460 |
); |
461 |
|
462 |
/** |
463 |
* Helper to select an option in a Select2 dropdown by index |
464 |
* Useful when the exact text is unknown or when needing to select a specific item by position |
465 |
* |
466 |
* @param {string} selector - jQuery-like selector for the original select element |
467 |
* @param {number} index - Index of the option to select (0-based) |
468 |
* @param {string} [searchText=null] - Optional text to search for before selecting |
469 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
470 |
* |
471 |
* @example |
472 |
* // Select the first item in dropdown |
473 |
* cy.selectFromSelect2ByIndex('#categorySelect', 0); |
474 |
* |
475 |
* @example |
476 |
* // Search first, then select by index |
477 |
* cy.selectFromSelect2ByIndex('#bookSelect', 2, 'Fiction'); |
478 |
* |
479 |
* @example |
480 |
* // Chain with assertions |
481 |
* cy.selectFromSelect2ByIndex('#authorSelect', 0) |
482 |
* .should('not.have.value', '') |
483 |
* .and('be.visible'); |
484 |
*/ |
485 |
Cypress.Commands.add( |
486 |
"selectFromSelect2ByIndex", |
487 |
(selector, index, searchText = null) => { |
488 |
return cy.get(selector).select2({ |
489 |
search: searchText, |
490 |
selectIndex: index, |
491 |
}); |
492 |
} |
493 |
); |
494 |
|
495 |
/** |
496 |
* Helper to select an option in a Select2 dropdown using a custom matcher function |
497 |
* Most flexible option for complex Select2 structures with nested elements or specific attributes |
498 |
* |
499 |
* @param {string} selector - jQuery-like selector for the original select element |
500 |
* @param {Function} matcherFn - Custom function to match against option content |
501 |
* @param {string} [searchText=null] - Optional text to search for before selecting |
502 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
503 |
* |
504 |
* @example |
505 |
* // Select option with specific data attribute |
506 |
* cy.selectFromSelect2WithMatcher('#bookSelect', |
507 |
* (option) => option.element.hasAttribute('data-special') && |
508 |
* option.text.includes('Special Edition'), |
509 |
* 'Lord of the Rings' |
510 |
* ); |
511 |
* |
512 |
* @example |
513 |
* // Select option that contains both title and author |
514 |
* cy.selectFromSelect2WithMatcher('#bookSelect', |
515 |
* (option) => option.text.includes('Tolkien') && option.text.includes('Hobbit'), |
516 |
* 'Tolkien' |
517 |
* ); |
518 |
* |
519 |
* @example |
520 |
* // Chain with other commands |
521 |
* cy.selectFromSelect2WithMatcher('#publisherSelect', |
522 |
* (option) => option.html.includes('<em>Premium</em>'), |
523 |
* 'Premium' |
524 |
* ).then(() => { |
525 |
* cy.get('#premium-options').should('be.visible'); |
526 |
* }); |
527 |
*/ |
528 |
Cypress.Commands.add( |
529 |
"selectFromSelect2WithMatcher", |
530 |
(selector, matcherFn, searchText = null) => { |
531 |
return cy.get(selector).select2({ |
532 |
search: searchText, |
533 |
matcher: matcherFn, |
534 |
}); |
535 |
} |
536 |
); |