index.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { ReactWrapper } from 'enzyme';
  2. import { IStyledComponent } from '../src/types';
  3. function assertElement(element: any) {
  4. if (!(element instanceof HTMLElement)) {
  5. throw new Error('Must pass a DOM element to find/findAll(element, styledComponent)"');
  6. }
  7. }
  8. function assertStyledComponent(styledComponent: any) {
  9. if (
  10. !styledComponent?.styledComponentId ||
  11. typeof styledComponent.styledComponentId !== 'string'
  12. ) {
  13. throw new Error(
  14. `${
  15. styledComponent.displayName || styledComponent.name || 'Component'
  16. } is not a styled component.`
  17. );
  18. }
  19. }
  20. export function enzymeFind(wrapper: ReactWrapper, styledComponent: IStyledComponent<'web', any>) {
  21. assertStyledComponent(styledComponent);
  22. return wrapper.find(`.${styledComponent.styledComponentId}`);
  23. }
  24. export function find(element: Element, styledComponent: IStyledComponent<'web', any>) {
  25. assertElement(element);
  26. assertStyledComponent(styledComponent);
  27. return element.querySelector(`.${styledComponent.styledComponentId}`);
  28. }
  29. export function findAll(element: Element, styledComponent: IStyledComponent<'web', any>) {
  30. assertElement(element);
  31. assertStyledComponent(styledComponent);
  32. return element.querySelectorAll(`.${styledComponent.styledComponentId}`);
  33. }