ui-router / react

🔼 UI-Router for React
https://ui-router.github.io/react/
MIT License
512 stars 128 forks source link

testing ui router with relative paths #1222

Open chiptus opened 4 months ago

chiptus commented 4 months ago

in my components, I have a link to some relative state ".custom". My tests fail No reference point given for path '.custom'

I'm using vitest (but had this problem also with jest), react 17

here's an example (silly, but shows the idea):

import { UISref, UIView } from '@uirouter/react';

import { withTestRouter } from '@/react/test-utils/withRouter';
import { render, screen } from '@/react-tools/test-utils';

function RelativePathLink() {
  return (
    <UISref to=".custom">
      <span>Link</span>
    </UISref>
  );
}

test('should render a link with relative path', () => {
  const WrappedComponent = withTestRouter(RelativePathLink, {
    stateConfig: [
      {
        name: 'parent',
        url: '/',

        component: () => (
          <>
            <div>parent</div>
            <UIView />
          </>
        ),
      },
      {
        name: 'parent.custom',
        url: 'custom',
      },
    ],
    route: 'parent',
  });

  render(<WrappedComponent />);

  expect(screen.getByText('Link')).toBeInTheDocument();
});

withTestRouter:

import { ComponentType } from 'react';
import {
  ReactStateDeclaration,
  UIRouter,
  UIRouterReact,
  UIView,
  hashLocationPlugin,
  servicesPlugin,
} from '@uirouter/react';

/**
 * A helper function to wrap a component with a UIRouter Provider.
 *
 * should only be used in tests
 */
export function withTestRouter<T>(
  WrappedComponent: ComponentType<T>,
  {
    route = '/',
    stateConfig = [],
  }: { route?: string; stateConfig?: Array<ReactStateDeclaration> } = {}
): ComponentType<T> {
  const router = new UIRouterReact();

  // router.trace.enable(Category.TRANSITION);
  router.plugin(servicesPlugin);
  router.plugin(hashLocationPlugin);

  // Set up your custom state configuration
  stateConfig.forEach((state) => router.stateRegistry.register(state));
  router.urlService.rules.initial({ state: route });

  // Try to create a nice displayName for React Dev Tools.
  const displayName =
    WrappedComponent.displayName || WrappedComponent.name || 'Component';

  function WrapperComponent(props: T & JSX.IntrinsicAttributes) {
    return (
      <UIRouter router={router}>
        <UIView />
        <WrappedComponent {...props} />
      </UIRouter>
    );
  }

  WrapperComponent.displayName = `withTestRouter(${displayName})`;

  return WrapperComponent;
}