react-dom/test-utils#Simulate JavaScript Examples

The following examples show how to use react-dom/test-utils#Simulate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FormField.driver.js    From wix-style-react with MIT License 6 votes vote down vote up
formFieldDriver = ({ element, dataHook }) => {
  const byHook = hook => element.querySelector(`[data-hook*="${hook}"]`);
  const charactersCounter = () => byHook('formfield-counter');

  const tooltipTestkit = tooltipDriverFactory({
    element: byHook(`${dataHook}-formfield-infoicon-tooltip`),
    eventTrigger: Simulate,
  });

  return {
    exists: () => !!element,
    element: () => element,
    getChildren: () => byHook('formfield-children'),
    getLabel: () => byHook('formfield-label'),
    isRequired: () => !!byHook('formfield-asterisk'),
    getLengthLeft: () => {
      const counter = charactersCounter();
      return counter ? parseInt(counter.innerHTML, 10) : null;
    },
    isLengthExceeded: () => {
      const counter = charactersCounter();
      if (counter) {
        const length = parseInt(counter.innerHTML, 10);
        return length < 0;
      }
      return false;
    },
    hasTooltip: () => tooltipTestkit.exists(),
    getInfoContent: () => {
      tooltipTestkit.mouseEnter();
      return tooltipTestkit.getContentElement().textContent;
    },
  };
}
Example #2
Source File: Ticker.js    From wix-style-react with MIT License 6 votes vote down vote up
tickerDriverFactory = component => {
  const handlers = {
    getUp: () => component.querySelector(`.${styles.up}`),
    getDown: () => component.querySelector(`.${styles.down}`),
    clickUp: () => Simulate.click(handlers.getUp()),
    clickDown: () => Simulate.click(handlers.getDown()),
    isUpDisabled: () => handlers.getUp().classList.contains(styles.disabled),
    isDownDisabled: () =>
      handlers.getDown().classList.contains(styles.disabled),
    exists: () => !!component,
  };
  return handlers;
}
Example #3
Source File: index.js    From wix-style-react with MIT License 6 votes vote down vote up
/**
 * Creates a `render` function that returns the same object as `@testing-library/react`'s render, but
 * with and extra `driver` property.
 *
 * The returned render function arguments:
 * @param [React.Element] jsx a jsx element to render
 * @param [object] options - render-options for @testing-library/react. The options may also contain a `dataHook` prop which if provided then the driver would be created with the element which is found by the dataHook. If not provided then it assumes that the rendered root element is the component's root element and it will be used for the driver.
 */
export function createRendererWithDriver(driverFactory, defaultOptions = {}) {
  const createDriver = ({ rendered, element, component }) =>
    driverFactory({
      element: element,
      wrapper: rendered.container,
      eventTrigger: Simulate,
      component,
    });
  return createRendererBase(createDriver, defaultOptions);
}
Example #4
Source File: Checkbox.uni.driver.js    From wix-style-react with MIT License 5 votes vote down vote up
checkboxUniDriverFactory = (base, body) => {
  const reactBase = ReactBase(base);
  const input = () => base.$('input');
  const isChecked = async () =>
    (await getDataCheckType(base)) === DATA_ATTR.CHECK_TYPES.CHECKED;
  const labelDriver = async () =>
    labelUniDriverFactory(base.$('[data-hook="checkbox-label"]'));
  const tooltipDriver = async () =>
    tooltipDriverFactory(base.$('[data-hook="checkbox-box"]'), body);

  return {
    ...baseUniDriverFactory(base),
    click: async () => {
      if (base.type === 'react') {
        // eslint-disable-next-line no-restricted-properties
        Simulate.change(await input().getNative(), {
          target: { checked: !(await isChecked()) },
        });
      } else {
        return base.click();
      }
    },
    /** trigger focus on the element */
    focus: reactBase.focus,
    /** trigger blur on the element */
    blur: reactBase.blur,
    /**
     * Focus related testing is done in e2e tests only.
     * @deprecated
     */
    hasFocusState: () => base.attr('data-focus'),
    isChecked,
    isDisabled: async () =>
      (await base.attr(DATA_ATTR.DATA_DISABLED)) === 'true',
    isIndeterminate: async () =>
      (await getDataCheckType(base)) === DATA_ATTR.CHECK_TYPES.INDETERMINATE,
    hasError: async () =>
      (await base.attr(DATA_ATTR.DATA_HAS_ERROR)) === 'true',
    getLabel: async () => (await labelDriver()).getLabelText(),
    getLabelDriver: () => labelDriver(),
    getErrorMessage: async () => {
      try {
        const newVar = await tooltipDriver();
        return newVar.getTooltipText();
      } catch (e) {
        throw new Error('Failed getting checkbox error message');
      }
    },
  };
}
Example #5
Source File: DropdownBase.private.uni.driver.js    From wix-style-react with MIT License 5 votes vote down vote up
dropdownBasePrivateDriverFactory = (base, body) => {
  const byDataHook = dataHook => base.$(`[data-hook="${dataHook}"]`);

  const getTargetElement = () => byDataHook('popover-element');
  const getContentElement = () => byDataHook('popover-content');

  const createDropdownLayoutDriver = () => dropdownLayoutDriverFactory(base);

  return {
    ...publicDriverFactory(base, body),

    /** Returns the native target element */
    getTargetElement: () => getTargetElement().getNative(),

    /** Returns the native DropdownLayout element */
    getDropdownElement: () => getContentElement().getNative(),

    /** Return `true` if the option is hovered by the mouse */
    isOptionHovered: async index =>
      createDropdownLayoutDriver().isOptionHovered(index),

    /** Return `true` if the option is selected */
    isOptionSelected: async index =>
      createDropdownLayoutDriver().isOptionSelected(index),

    /** Trigger a keyDown event on the target element */
    keyDown: async key => {
      if (base.type === 'react') {
        Simulate.keyDown(await getTargetElement().getNative(), { key });
      }
    },

    /** Perform a mouseEnter on the target element */
    mouseEnterTarget: async () => {
      if (base.type === 'react') {
        Simulate.mouseEnter(
          (await getTargetElement().getNative()).childNodes[0],
        );
      }
    },

    /** Perform a mouseEnter on the target element */
    mouseLeaveTarget: async () => {
      if (base.type === 'react') {
        Simulate.mouseLeave(
          (await getTargetElement().getNative()).childNodes[0],
        );
      }
    },
  };
}
Example #6
Source File: ReactBase.js    From wix-style-react with MIT License 4 votes vote down vote up
/**
 *Temporary workaround for implementing missing Unidriver methods in React/DOM only.
 *
 * @param {UniDriver} base
 */
export function ReactBase(base) {
  const htmlElement = () => {
    if (base.type !== 'react') {
      throw new Error('Supported only in React/DOM.');
    }
    return base.getNative();
  };

  const pendingUnidriverFeatures = {
    isFocus: async () => {
      return document.activeElement === (await htmlElement());
    },
    paste: async () => Simulate.paste(await htmlElement()),
    select: async selectedIndex =>
      Simulate.change(await htmlElement(), {
        target: { selectedIndex, value: '' },
      }),
  };

  const unidriverRejected = {
    // Event Simulation
    focus: async () => {
      const elm = await htmlElement();
      elm.focus();
      Simulate.focus(elm); // TODO: Is this redundant?
    },
    blur: async () => {
      const elm = await htmlElement();
      elm.blur();
      Simulate.blur(elm); // TODO: Is this redundant?
    },
  };

  // Instead of using this methods you should use proper data hooks
  // and data attributes the query the required elements
  const deprecated = {
    _DEPRECATED_getClassList: async () => (await htmlElement()).classList,
    /** @returns {array} array of children unidrivers */
    _DEPRECATED_children: async () => {
      const ch = (await htmlElement()).children;
      const uniChildren = [];
      for (let i = 0; i < ch.length; i++) {
        uniChildren.push(reactUniDriver(ch[i]));
      }
      return uniChildren;
    },
  };

  const shouldBePrivate = {
    keyUp: async eventData => Simulate.keyUp(await htmlElement(), eventData),
    keyDown: async eventData =>
      Simulate.keyDown(await htmlElement(), eventData),
    mouseEnter: async eventData =>
      Simulate.mouseEnter(await htmlElement(), eventData),
    mouseLeave: async eventData =>
      Simulate.mouseLeave(await htmlElement(), eventData),
  };

  const _private = {
    mouseDown: async eventData =>
      Simulate.mouseDown(await htmlElement(), eventData),
    mouseOver: async eventData =>
      Simulate.mouseOver(await htmlElement(), eventData),
    mouseOut: async eventData =>
      Simulate.mouseOut(await htmlElement(), eventData),
    compositionStart: async () =>
      Simulate.compositionStart(await htmlElement()),
    compositionEnd: async () => Simulate.compositionEnd(await htmlElement()),
  };

  return {
    ...pendingUnidriverFeatures,
    ...unidriverRejected,
    ...deprecated,
    ...shouldBePrivate,
    _private, // should be used inside private drivers only
  };
}