|
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.getSelect2('#mySelect') |
| 16 |
* .select2({ search: 'foo' }) |
| 17 |
* .select2({ select: 'FooBar' }); |
| 18 |
* |
| 19 |
* cy.getSelect2('#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.getSelect2('#mySelect') |
| 47 |
* .select2({ search: 'foo' }) |
| 48 |
* .select2({ select: 'FooBar' }); |
| 49 |
* |
| 50 |
* @example |
| 51 |
* // With custom matcher |
| 52 |
* cy.getSelect2('#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, // Search text to enter in the search box |
| 66 |
select: null, // Text to select or object with matcher options |
| 67 |
selectIndex: null, // Index of the option to select |
| 68 |
selector: null, // CSS selector to find the select element (when not using subject) |
| 69 |
clearSelection: false, // Whether to clear the current selection first |
| 70 |
matcher: null, // Custom matcher function for complex option selection |
| 71 |
timeout: 10000, // Timeout for AJAX responses |
| 72 |
multiple: false, // Whether the select2 allows multiple selections |
| 73 |
minSearchLength: 3, // Minimum length of search text needed for Ajax select2 |
| 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 |
// Try to get the ID either from the element or from the stored data attribute |
| 100 |
const selectId = $el.attr("id") || $el.data("select2-helper-id"); |
| 101 |
|
| 102 |
if (!selectId) { |
| 103 |
throw new Error( |
| 104 |
"Select element must have an ID attribute for the Select2 helper to work correctly" |
| 105 |
); |
| 106 |
} |
| 107 |
|
| 108 |
// Find the Select2 container - based on the actual DOM structure |
| 109 |
// Look for a span.select2-container that's a sibling of the original select |
| 110 |
cy.get(`select#${selectId}`) |
| 111 |
.siblings(".select2-container") |
| 112 |
.first() |
| 113 |
.then($container => { |
| 114 |
// Handle clearing the selection if requested |
| 115 |
if (config.clearSelection) { |
| 116 |
// Use Select2's API to clear the selection |
| 117 |
cy.window().then(win => { |
| 118 |
// Use jQuery to access the Select2 element and clear it programmatically |
| 119 |
win.$(`select#${selectId}`) |
| 120 |
.val(null) |
| 121 |
.trigger("change"); |
| 122 |
}); |
| 123 |
// Return early if we're just clearing |
| 124 |
if ( |
| 125 |
config.search === null && |
| 126 |
config.select === null && |
| 127 |
config.selectIndex === null && |
| 128 |
config.matcher === null |
| 129 |
) { |
| 130 |
return; |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
// Find the select2-selection element within the container and click it |
| 135 |
cy.wrap($container) |
| 136 |
.find(".select2-selection") |
| 137 |
.first() |
| 138 |
.click({ force: true }); |
| 139 |
|
| 140 |
// Handle search functionality |
| 141 |
if (config.search !== null) { |
| 142 |
// Find the search field in the dropdown (which is appended to body) |
| 143 |
cy.get( |
| 144 |
".select2-search--dropdown .select2-search__field" |
| 145 |
) |
| 146 |
.first() |
| 147 |
.should("be.visible") |
| 148 |
.type(config.search, { force: true }); |
| 149 |
|
| 150 |
// If this is an Ajax select2 that requires minimum characters |
| 151 |
if (config.search.length < config.minSearchLength) { |
| 152 |
cy.log( |
| 153 |
`Warning: Search text "${config.search}" may be too short for Ajax select2 (minimum typically ${config.minSearchLength} characters)` |
| 154 |
); |
| 155 |
|
| 156 |
// Check if we see the "Please enter X or more characters" message |
| 157 |
cy.get(".select2-results__message").then( |
| 158 |
$message => { |
| 159 |
if ( |
| 160 |
$message.length > 0 && |
| 161 |
$message.text().includes("character") |
| 162 |
) { |
| 163 |
cy.log( |
| 164 |
"Detected minimum character requirement message. Search string may be too short." |
| 165 |
); |
| 166 |
} |
| 167 |
} |
| 168 |
); |
| 169 |
} |
| 170 |
|
| 171 |
// Wait for results to load - use a longer timeout for AJAX-based Select2 |
| 172 |
cy.get(".select2-results__options", { |
| 173 |
timeout: config.timeout, |
| 174 |
}).should("exist"); |
| 175 |
|
| 176 |
// Wait a moment for AJAX responses to complete |
| 177 |
cy.wait(300); // Small wait to ensure AJAX response completes |
| 178 |
|
| 179 |
// Check for no results to provide helpful error |
| 180 |
cy.get(".select2-results__option").then($options => { |
| 181 |
if ( |
| 182 |
$options.length === 0 || |
| 183 |
($options.length === 1 && |
| 184 |
$options |
| 185 |
.first() |
| 186 |
.text() |
| 187 |
.includes("No results")) || |
| 188 |
($options.length === 1 && |
| 189 |
$options |
| 190 |
.first() |
| 191 |
.text() |
| 192 |
.includes("Please enter")) |
| 193 |
) { |
| 194 |
cy.log( |
| 195 |
`Warning: No results found for search: "${config.search}"` |
| 196 |
); |
| 197 |
} |
| 198 |
}); |
| 199 |
} |
| 200 |
|
| 201 |
// Handle selection based on the provided options |
| 202 |
if ( |
| 203 |
config.select !== null || |
| 204 |
config.selectIndex !== null || |
| 205 |
config.matcher !== null |
| 206 |
) { |
| 207 |
// Get the results options |
| 208 |
cy.get(".select2-results__option").then($options => { |
| 209 |
if ( |
| 210 |
$options.length === 0 || |
| 211 |
($options.length === 1 && |
| 212 |
$options |
| 213 |
.first() |
| 214 |
.text() |
| 215 |
.includes("No results")) || |
| 216 |
($options.length === 1 && |
| 217 |
$options |
| 218 |
.first() |
| 219 |
.text() |
| 220 |
.includes("Please enter")) |
| 221 |
) { |
| 222 |
throw new Error( |
| 223 |
`No selectable options found for search: "${config.search}"` |
| 224 |
); |
| 225 |
} |
| 226 |
|
| 227 |
let $optionToSelect; |
| 228 |
|
| 229 |
// Select by index |
| 230 |
if (config.selectIndex !== null) { |
| 231 |
if ( |
| 232 |
config.selectIndex < 0 || |
| 233 |
config.selectIndex >= $options.length |
| 234 |
) { |
| 235 |
throw new Error( |
| 236 |
`Select2: index ${config.selectIndex} out of bounds (0-${$options.length - 1})` |
| 237 |
); |
| 238 |
} |
| 239 |
$optionToSelect = $options.eq( |
| 240 |
config.selectIndex |
| 241 |
); |
| 242 |
} |
| 243 |
// Select by custom matcher function |
| 244 |
else if ( |
| 245 |
config.matcher !== null && |
| 246 |
typeof config.matcher === "function" |
| 247 |
) { |
| 248 |
for (let i = 0; i < $options.length; i++) { |
| 249 |
const $option = $options.eq(i); |
| 250 |
const optionContent = { |
| 251 |
text: $option.text().trim(), |
| 252 |
html: $option.html(), |
| 253 |
element: $option[0], |
| 254 |
}; |
| 255 |
|
| 256 |
if (config.matcher(optionContent, i)) { |
| 257 |
$optionToSelect = $option; |
| 258 |
break; |
| 259 |
} |
| 260 |
} |
| 261 |
} |
| 262 |
// Select by text (default) |
| 263 |
else if (config.select !== null) { |
| 264 |
// If config.select is a string, use default matching |
| 265 |
if (typeof config.select === "string") { |
| 266 |
const selectText = config.select; |
| 267 |
|
| 268 |
// Try exact match first |
| 269 |
const exactMatch = $options.filter( |
| 270 |
(i, el) => |
| 271 |
Cypress.$(el).text().trim() === |
| 272 |
selectText |
| 273 |
); |
| 274 |
|
| 275 |
if (exactMatch.length) { |
| 276 |
$optionToSelect = exactMatch.first(); |
| 277 |
} else { |
| 278 |
// Fall back to partial match |
| 279 |
const partialMatches = $options.filter( |
| 280 |
(i, el) => |
| 281 |
Cypress.$(el) |
| 282 |
.text() |
| 283 |
.trim() |
| 284 |
.includes(selectText) |
| 285 |
); |
| 286 |
|
| 287 |
if (partialMatches.length) { |
| 288 |
$optionToSelect = |
| 289 |
partialMatches.first(); |
| 290 |
} |
| 291 |
} |
| 292 |
} |
| 293 |
// Handle object format for advanced matching |
| 294 |
else if (typeof config.select === "object") { |
| 295 |
const matchType = |
| 296 |
config.select.matchType || "partial"; // 'exact', 'partial', 'startsWith', 'endsWith' |
| 297 |
const text = config.select.text; |
| 298 |
|
| 299 |
if (!text) { |
| 300 |
throw new Error( |
| 301 |
'When using object format for selection, "text" property is required' |
| 302 |
); |
| 303 |
} |
| 304 |
|
| 305 |
let matcher; |
| 306 |
switch (matchType) { |
| 307 |
case "exact": |
| 308 |
matcher = optText => |
| 309 |
optText === text; |
| 310 |
break; |
| 311 |
case "startsWith": |
| 312 |
matcher = optText => |
| 313 |
optText.startsWith(text); |
| 314 |
break; |
| 315 |
case "endsWith": |
| 316 |
matcher = optText => |
| 317 |
optText.endsWith(text); |
| 318 |
break; |
| 319 |
case "partial": |
| 320 |
default: |
| 321 |
matcher = optText => |
| 322 |
optText.includes(text); |
| 323 |
} |
| 324 |
|
| 325 |
for (let i = 0; i < $options.length; i++) { |
| 326 |
const $option = $options.eq(i); |
| 327 |
const optionText = $option |
| 328 |
.text() |
| 329 |
.trim(); |
| 330 |
|
| 331 |
if (matcher(optionText)) { |
| 332 |
$optionToSelect = $option; |
| 333 |
break; |
| 334 |
} |
| 335 |
} |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
// If we found an option to select, click it |
| 340 |
if ($optionToSelect) { |
| 341 |
cy.wrap($optionToSelect).click({ force: true }); |
| 342 |
cy.wait(300); |
| 343 |
|
| 344 |
// Check that the original select has a value (to verify selection worked) |
| 345 |
// We just check that it has some value, not a specific value |
| 346 |
cy.get(`select#${selectId}`).should($el => { |
| 347 |
expect($el.val()).to.not.be.null; |
| 348 |
expect($el.val()).to.not.equal(""); |
| 349 |
}); |
| 350 |
} else { |
| 351 |
throw new Error( |
| 352 |
`Could not find any option matching the selection criteria. Search: "${config.search}", Select: "${config.select}"` |
| 353 |
); |
| 354 |
} |
| 355 |
}); |
| 356 |
} |
| 357 |
}); |
| 358 |
}); |
| 359 |
} |
| 360 |
); |
| 361 |
|
| 362 |
/** |
| 363 |
* Helper to get a Select2 dropdown by any jQuery-like selector |
| 364 |
* This is the recommended starting point for chainable Select2 operations |
| 365 |
* |
| 366 |
* @param {string} selector - jQuery-like selector for the original select element |
| 367 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
| 368 |
* |
| 369 |
* @example |
| 370 |
* // Chain multiple Select2 operations |
| 371 |
* cy.getSelect2('#bookSelect') |
| 372 |
* .select2({ search: 'JavaScript' }) |
| 373 |
* .select2({ select: 'JavaScript: The Good Parts' }); |
| 374 |
* |
| 375 |
* @example |
| 376 |
* // Chain with standard Cypress assertions |
| 377 |
* cy.getSelect2('#categorySelect') |
| 378 |
* .select2({ select: 'Fiction' }) |
| 379 |
* .should('have.value', 'fiction'); |
| 380 |
*/ |
| 381 |
Cypress.Commands.add("getSelect2", selector => { |
| 382 |
return cy.get(selector); |
| 383 |
}); |
| 384 |
|
| 385 |
/** |
| 386 |
* Helper to clear a Select2 selection |
| 387 |
* Can be used as a standalone command or as part of a chain |
| 388 |
* |
| 389 |
* @param {string} selector - jQuery-like selector for the original select element |
| 390 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
| 391 |
* |
| 392 |
* @example |
| 393 |
* // Standalone usage |
| 394 |
* cy.clearSelect2('#tagSelect'); |
| 395 |
* |
| 396 |
* @example |
| 397 |
* // As part of a chain |
| 398 |
* cy.getSelect2('#tagSelect') |
| 399 |
* .select2({ select: 'Mystery' }) |
| 400 |
* .clearSelect2('#tagSelect') |
| 401 |
* .select2({ select: 'Fantasy' }); |
| 402 |
*/ |
| 403 |
Cypress.Commands.add("clearSelect2", selector => { |
| 404 |
return cy.getSelect2(selector).select2({ clearSelection: true }); |
| 405 |
}); |
| 406 |
|
| 407 |
/** |
| 408 |
* Helper to search in a Select2 dropdown without making a selection |
| 409 |
* Useful for testing search functionality or as part of a multi-step interaction |
| 410 |
* |
| 411 |
* @param {string} selector - jQuery-like selector for the original select element |
| 412 |
* @param {string} searchText - Text to search for |
| 413 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
| 414 |
* |
| 415 |
* @example |
| 416 |
* // Standalone usage to test search functionality |
| 417 |
* cy.searchSelect2('#authorSelect', 'Gaiman'); |
| 418 |
* |
| 419 |
* @example |
| 420 |
* // Chained with selection - more reliable for AJAX Select2s |
| 421 |
* cy.getSelect2('#publisherSelect') |
| 422 |
* .searchSelect2('#publisherSelect', "O'Reilly") |
| 423 |
* .wait(500) // Allow time for AJAX results |
| 424 |
* .select2({ selectIndex: 0 }); |
| 425 |
*/ |
| 426 |
Cypress.Commands.add("searchSelect2", (selector, searchText) => { |
| 427 |
return cy.getSelect2(selector).select2({ search: searchText }); |
| 428 |
}); |
| 429 |
|
| 430 |
/** |
| 431 |
* Helper to select an option in a Select2 dropdown by text |
| 432 |
* Combines search and select in one command, but can be less reliable for AJAX Select2s |
| 433 |
* |
| 434 |
* @param {string} selector - jQuery-like selector for the original select element |
| 435 |
* @param {string|Object} selectText - Text to select or object with matcher options |
| 436 |
* @param {string} [searchText=null] - Optional text to search for before selecting |
| 437 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
| 438 |
* |
| 439 |
* @example |
| 440 |
* // Basic usage |
| 441 |
* cy.selectFromSelect2('#authorSelect', 'J.R.R. Tolkien'); |
| 442 |
* |
| 443 |
* @example |
| 444 |
* // With search text |
| 445 |
* cy.selectFromSelect2('#publisherSelect', 'O\'Reilly Media', 'O\'Reilly'); |
| 446 |
* |
| 447 |
* @example |
| 448 |
* // Using advanced matching options |
| 449 |
* cy.selectFromSelect2('#bookSelect', |
| 450 |
* { text: 'The Hobbit', matchType: 'exact' }, |
| 451 |
* 'Hobbit' |
| 452 |
* ); |
| 453 |
* |
| 454 |
* @example |
| 455 |
* // Chainable with other Cypress commands |
| 456 |
* cy.selectFromSelect2('#categorySelect', 'Fiction') |
| 457 |
* .should('have.value', 'fiction') |
| 458 |
* .and('be.visible'); |
| 459 |
*/ |
| 460 |
Cypress.Commands.add( |
| 461 |
"selectFromSelect2", |
| 462 |
(selector, selectText, searchText = null) => { |
| 463 |
return cy.getSelect2(selector).select2({ |
| 464 |
search: searchText, |
| 465 |
select: selectText, |
| 466 |
}); |
| 467 |
} |
| 468 |
); |
| 469 |
|
| 470 |
/** |
| 471 |
* Helper to select an option in a Select2 dropdown by index |
| 472 |
* Useful when the exact text is unknown or when needing to select a specific item by position |
| 473 |
* |
| 474 |
* @param {string} selector - jQuery-like selector for the original select element |
| 475 |
* @param {number} index - Index of the option to select (0-based) |
| 476 |
* @param {string} [searchText=null] - Optional text to search for before selecting |
| 477 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
| 478 |
* |
| 479 |
* @example |
| 480 |
* // Select the first item in dropdown |
| 481 |
* cy.selectFromSelect2ByIndex('#categorySelect', 0); |
| 482 |
* |
| 483 |
* @example |
| 484 |
* // Search first, then select by index |
| 485 |
* cy.selectFromSelect2ByIndex('#bookSelect', 2, 'Fiction'); |
| 486 |
* |
| 487 |
* @example |
| 488 |
* // Chain with assertions |
| 489 |
* cy.selectFromSelect2ByIndex('#authorSelect', 0) |
| 490 |
* .should('not.have.value', '') |
| 491 |
* .and('be.visible'); |
| 492 |
*/ |
| 493 |
Cypress.Commands.add( |
| 494 |
"selectFromSelect2ByIndex", |
| 495 |
(selector, index, searchText = null) => { |
| 496 |
return cy.getSelect2(selector).select2({ |
| 497 |
search: searchText, |
| 498 |
selectIndex: index, |
| 499 |
}); |
| 500 |
} |
| 501 |
); |
| 502 |
|
| 503 |
/** |
| 504 |
* Helper to select an option in a Select2 dropdown using a custom matcher function |
| 505 |
* Most flexible option for complex Select2 structures with nested elements or specific attributes |
| 506 |
* |
| 507 |
* @param {string} selector - jQuery-like selector for the original select element |
| 508 |
* @param {Function} matcherFn - Custom function to match against option content |
| 509 |
* @param {string} [searchText=null] - Optional text to search for before selecting |
| 510 |
* @returns {Cypress.Chainable} - Returns a chainable Cypress object for further commands |
| 511 |
* |
| 512 |
* @example |
| 513 |
* // Select option with specific data attribute |
| 514 |
* cy.selectFromSelect2WithMatcher('#bookSelect', |
| 515 |
* (option) => option.element.hasAttribute('data-special') && |
| 516 |
* option.text.includes('Special Edition'), |
| 517 |
* 'Lord of the Rings' |
| 518 |
* ); |
| 519 |
* |
| 520 |
* @example |
| 521 |
* // Select option that contains both title and author |
| 522 |
* cy.selectFromSelect2WithMatcher('#bookSelect', |
| 523 |
* (option) => option.text.includes('Tolkien') && option.text.includes('Hobbit'), |
| 524 |
* 'Tolkien' |
| 525 |
* ); |
| 526 |
* |
| 527 |
* @example |
| 528 |
* // Chain with other commands |
| 529 |
* cy.selectFromSelect2WithMatcher('#publisherSelect', |
| 530 |
* (option) => option.html.includes('<em>Premium</em>'), |
| 531 |
* 'Premium' |
| 532 |
* ).then(() => { |
| 533 |
* cy.get('#premium-options').should('be.visible'); |
| 534 |
* }); |
| 535 |
*/ |
| 536 |
Cypress.Commands.add( |
| 537 |
"selectFromSelect2WithMatcher", |
| 538 |
(selector, matcherFn, searchText = null) => { |
| 539 |
return cy.getSelect2(selector).select2({ |
| 540 |
search: searchText, |
| 541 |
matcher: matcherFn, |
| 542 |
}); |
| 543 |
} |
| 544 |
); |