select-new.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. export function getSelector(options = {}) {
  2. let selector = '';
  3. if (options.selector) {
  4. return options.selector;
  5. }
  6. if (options.name) {
  7. selector = `[name="${options.name}"]`;
  8. }
  9. const field = `Select${options.control ? 'Control' : 'Field'}`;
  10. return `${field}${selector}`;
  11. }
  12. export function openMenu(wrapper, options = {}) {
  13. const selector = getSelector(options);
  14. const control = wrapper.find(`${selector} SelectContainer Control`).at(options.at || 0);
  15. control.prop('innerProps').onMouseDown({target: {tagName: 'INPUT'}});
  16. control.find('input').simulate('focus');
  17. return wrapper;
  18. }
  19. export function clearValue(wrapper) {
  20. wrapper.find('.Select-clear-zone').simulate('mouseDown', {button: 0});
  21. }
  22. export function findOption(wrapper, {value, label} = {}, options) {
  23. const selector = getSelector(options);
  24. const valueSelector = value ? 'value' : 'label';
  25. return wrapper.find(`${selector} Option[${valueSelector}="${value || label}"]`);
  26. }
  27. export function selectByLabel(wrapper, label, options = {}) {
  28. openMenu(wrapper, options);
  29. findOption(wrapper, {label}, options).at(0).simulate('click');
  30. }
  31. export function getOptionByLabel(wrapper, label, options = {}) {
  32. openMenu(wrapper, options);
  33. return findOption(wrapper, {label}, options).at(0);
  34. }
  35. export function selectByValue(wrapper, value, options = {}) {
  36. openMenu(wrapper, options);
  37. findOption(wrapper, {value}, options).at(0).simulate('click');
  38. }
  39. // used for the text input to replicate a user typing
  40. export function changeInputValue(element, value) {
  41. element.instance().value = value;
  42. element.simulate('change', {target: {value}});
  43. }
  44. export async function selectByQuery(wrapper, query, options = {}) {
  45. openMenu(wrapper, options);
  46. const selector = getSelector({...options, control: true});
  47. const input = wrapper.find(`${selector} input[type="text"]`);
  48. changeInputValue(input, query);
  49. await tick(); // Hit the mock URL.
  50. selectByValue(wrapper, query, options);
  51. }
  52. export async function selectByValueAsync(wrapper, value, options = {}) {
  53. openMenu(wrapper, options);
  54. await tick();
  55. wrapper.update();
  56. findOption(wrapper, {value}, options).at(0).simulate('click');
  57. }