Skip to content

testing ui router with relative paths #1222

Description

@chiptus

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;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions