react-router-dom#MemoryRouter TypeScript Examples

The following examples show how to use react-router-dom#MemoryRouter. 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: test-utils.tsx    From crossfeed with Creative Commons Zero v1.0 Universal 7 votes vote down vote up
customRender = (ui: any, options: CustomRenderOptions = {}) => {
  const { initialHistory, authContext, ...rest } = options;

  // Provide any context that the components may be expecting
  const Wrapper: React.FC = ({ children }) => (
    <CFThemeProvider>
      <MemoryRouter initialEntries={initialHistory}>
        <AuthContext.Provider
          value={{
            ...authCtx,
            ...authContext
          }}
        >
          {children}
        </AuthContext.Provider>
      </MemoryRouter>
    </CFThemeProvider>
  );
  return render(ui, { wrapper: Wrapper, ...rest });
}
Example #2
Source File: test-utils.tsx    From solo with MIT License 7 votes vote down vote up
customRender = (ui: any, options: CustomRenderOptions = {}) => {
  const { initialHistory, authContext, ...rest } = options;

  // Provide any context that the components may be expecting
  const Wrapper: React.FC = ({ children }) => (
    <MemoryRouter initialEntries={initialHistory}>
      <AuthContext.Provider
        value={{
          ...defaultAuthContext,
          ...authContext
        }}
      >
        {children}
      </AuthContext.Provider>
    </MemoryRouter>
  );
  return render(ui, { wrapper: Wrapper, ...rest });
}
Example #3
Source File: test-utils.tsx    From iplocate with MIT License 7 votes vote down vote up
customRender = (ui: any, options: CustomRenderOptions = {}) => {
  const { initialHistory, ...rest } = options;

  // Provide any context that the components may be expecting
  const Wrapper: React.FC = ({ children }) => (
    <MemoryRouter initialEntries={initialHistory}>
      <ThemeProvider>{children}</ThemeProvider>
    </MemoryRouter>
  );
  return render(ui, { wrapper: Wrapper, ...rest });
}
Example #4
Source File: TaskListLabel.test.cypress.tsx    From metaflow-ui with Apache License 2.0 6 votes vote down vote up
TestWrapper: React.FC<{ route?: string }> = ({ children, route = '/' }) => {
  return (
    <ThemeProvider theme={theme}>
      <MemoryRouter initialEntries={[route]}>
        <QueryParamProvider ReactRouterRoute={Route}>{children}</QueryParamProvider>
      </MemoryRouter>
    </ThemeProvider>
  );
}
Example #5
Source File: Logo.test.tsx    From Fashionista with MIT License 6 votes vote down vote up
describe("The component Logo", () => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const AllTheProviders = ({ children }: any) => {
    return <MemoryRouter>{children}</MemoryRouter>;
  };

  const mockedProps = { height: 40, width: 120 };

  it("Should render Logo component passing height and width", () => {
    render(<Logo {...mockedProps} />, {
      wrapper: AllTheProviders,
    });

    expect(screen.getByRole("img")).toHaveAttribute("width", "120");
    expect(screen.getByRole("img")).toHaveAttribute("height", "40");
  });
});
Example #6
Source File: test.moun.helper.tsx    From frontend with Apache License 2.0 6 votes vote down vote up
mountVrtComponent = ({
  component,
  memoryRouterProps = {
    initialEntries: ["/"],
  },
  path = "/",
}: {
  component: React.ReactElement;
  memoryRouterProps?: MemoryRouterProps;
  path?: string;
}) =>
  mount(
    <MemoryRouter {...memoryRouterProps}>
      <Routes>
        <Route
          path={path}
          element={
            <SnackbarProvider>
              <UserProvider>
                <ProjectProvider>
                  <BuildProvider>
                    <HelpProvider>
                      <TestRunProvider>{component}</TestRunProvider>
                    </HelpProvider>
                  </BuildProvider>
                </ProjectProvider>
              </UserProvider>
            </SnackbarProvider>
          }
        />
      </Routes>
    </MemoryRouter>,
    {
      cssFiles: ["src/index.css"],
    }
  )
Example #7
Source File: ArticlePreview.test.tsx    From ts-redux-react-realworld-example-app with MIT License 6 votes vote down vote up
it('Favorite button should be outlined if not favorited', () => {
  render(
    <MemoryRouter>
      <ArticlePreview article={defaultArticle} isSubmitting={false} />
    </MemoryRouter>
  );

  expect(screen.getByLabelText('Toggle Favorite').className.split(' ')).toContain('btn-outline-primary');
});
Example #8
Source File: createApp.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
describe('Optional ThemeProvider', () => {
  it('should render app with user-provided ThemeProvider', async () => {
    const components = {
      NotFoundErrorPage: () => null,
      BootErrorPage: () => null,
      Progress: () => null,
      Router: MemoryRouter,
      ErrorBoundaryFallback: () => null,
      ThemeProvider: ({ children }: PropsWithChildren<{}>) => (
        <main role="main">{children}</main>
      ),
    };

    const App = createApp({ components }).getProvider();

    await renderWithEffects(<App />);

    expect(screen.getByRole('main')).toBeInTheDocument();
  });
});
Example #9
Source File: RenderDetail.test.tsx    From ke with MIT License 6 votes vote down vote up
test('Render detail mount', () => {
  jest.spyOn(React, 'useEffect').mockImplementation(() => ({ data: { patient: { last_name: 'Test' } } }))

  const component = mount(
    <MemoryRouter initialEntries={['/test/']}>
      <ChakraProvider>
        <RenderDetail resourceName="test" admin={testAdmin} provider={testProvider} user={{}} analytics={undefined} />
      </ChakraProvider>
    </MemoryRouter>
  )

  expect(component.find('ArrowLeft').length).toEqual(1)
  expect(component.find('div[data-test-id="testAdmin"]').length).toEqual(1)
})
Example #10
Source File: DemoApp.tsx    From clearflask with Apache License 2.0 6 votes vote down vote up
render() {
    return (
      <MemoryRouter initialEntries={this.props.intialSubPath ? [`${this.props.intialSubPath || '/'}`] : undefined}>
        <Route path="/" render={props => (
          <>
            {this.props.onPathChange && (
              <Route path='/' render={routeProps => {
                this.props.onPathChange?.(routeProps.location.pathname)
                return null;
              }} />
            )}
            {this.props.forcePathSubscribe && (
              <ForceUrl forcePathSubscribe={this.props.forcePathSubscribe} />
            )}
            <App
              {...props}
              slug={this.props.server.getStore().getState().conf.conf?.slug!}
              supressCssBaseline
              isInsideContainer
              serverOverride={this.props.server}
              settings={this.props.settings}
            />
          </>
        )} />
      </MemoryRouter>
    );
  }
Example #11
Source File: CreateAccount.slow.spec.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
renderAccounts = () => {
  const memoryStore = new MemoryStore();

  return render(
    <MemoryRouter>
      <ThemeProvider theme={lightTheme}>
        <Api store={memoryStore}
          url={`ws://127.0.0.1:${SUBSTRATE_PORT}`}>
          <WaitForApi>
            <div>
              <AccountsApp basePath='/accounts'
                onStatusChange={() => { /* */
                }}/>
            </div>
          </WaitForApi>
        </Api>
      </ThemeProvider>
    </MemoryRouter>
  );
}
Example #12
Source File: Setup.test.tsx    From legend-studio with Apache License 2.0 6 votes vote down vote up
test(
  integrationTest(
    'Shows project selector properly when there are at least 1 project',
  ),
  async () => {
    MOBX__enableSpyOrMock();
    jest
      .spyOn(sdlcServerClient, 'getProjects')
      .mockResolvedValueOnce([TEST_DATA__DefaultSDLCInfo.project])
      .mockResolvedValueOnce([]);
    MOBX__disableSpyOrMock();
    TEST__provideMockedWebApplicationNavigator();

    const { queryByText } = render(
      <MemoryRouter>
        <TEST__ApplicationStoreProvider
          config={TEST__getTestStudioConfig()}
          pluginManager={LegendStudioPluginManager.create()}
        >
          <TEST__SDLCServerClientProvider>
            <Setup />
          </TEST__SDLCServerClientProvider>
        </TEST__ApplicationStoreProvider>
      </MemoryRouter>,
    );

    // NOTE: react-select is not like a normal input box where we could set the placeholder, so we just
    // cannot use `queryByPlaceholderText` but have to use `queryByText`
    await waitFor(() =>
      expect(queryByText('Choose an existing project')).not.toBeNull(),
    );
  },
);
Example #13
Source File: AppBar.test.tsx    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
it('selects the matching nav-tab', async () => {
  const { getByText } = render(
    <MemoryRouter initialEntries={['/bar']}>
      <AppBar
        routes={[
          {
            label: 'foo',
            path: '/foo',
            showInNav: true,
            component: React.Fragment,
            exact: false,
          },
          {
            label: 'bar',
            path: '/bar',
            showInNav: true,
            component: React.Fragment,
            exact: false,
          },
        ]}
      />
    </MemoryRouter>
  );

  await act(() => delay(300)); // Wait for tab indicator async DOM updates.

  expect(isTabActive(getByText('foo'))).toBe(false);
  expect(isTabActive(getByText('bar'))).toBe(true);
});
Example #14
Source File: utils.tsx    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
renderWithRouter = (element: ReactElement) => render(element, { wrapper: MemoryRouter })
Example #15
Source File: Organization.test.tsx    From glific-frontend with GNU Affero General Public License v3.0 6 votes vote down vote up
test('it should render component and show error messages', () => {
  const { container } = render(
    <MockedProvider addTypename={false}>
      <MemoryRouter>
        <Organization {...props} errorMessage={{ global: 'Something went wrong' }} />
      </MemoryRouter>
    </MockedProvider>
  );

  const registration = screen.getByTestId('RegistrationContainer');
  expect(registration).toBeInTheDocument();

  const captcha = screen.getByTestId('recaptcha-sign-in');
  expect(captcha).toBeInTheDocument();

  // We can't submit the form as we don't have correct api key
  // May be we should start using github environment variables and store api key
  // comment below till we find a way to test this.
  // const submit = screen.getByTestId('SubmitButton');

  // act(() => {
  //   UserEvent.click(captcha);
  //   UserEvent.click(submit);
  // });

  // expect(container.getElementsByClassName('ErrorMessage')[0]).toBeInTheDocument();
});
Example #16
Source File: Breadcrumb.test.tsx    From chroma-react with MIT License 6 votes vote down vote up
test('it renders a Breadcrumb', async () => {
  const props = getBaseProps();
  const { findByTestId } = renderWithTheme(
    <MemoryRouter>
      <Breadcrumb {...props} data-testid={testId} />
    </MemoryRouter>
  );
  const breadcrumb = await findByTestId(testId);
  expect(breadcrumb).toBeInTheDocument();
});
Example #17
Source File: Initialize.test.tsx    From mail-my-ballot with Apache License 2.0 6 votes vote down vote up
test('Initialize picks up parameters', () => {
  const utmFields = {
    utm_source: 'source1234',      //eslint-disable-line @typescript-eslint/camelcase
    utm_medium: 'medium1234',      //eslint-disable-line @typescript-eslint/camelcase
    utm_campaign: 'campaign1234',  //eslint-disable-line @typescript-eslint/camelcase
    utm_term: 'term1234',          //eslint-disable-line @typescript-eslint/camelcase
    utm_content: 'content1234',    //eslint-disable-line @typescript-eslint/camelcase
  }

  const params = Object.entries(utmFields).map(([key, val]) => `${key}=${val}`).join('&')

  render(
    // Using MemoryRouter is recommended way to test react-router-dom
    // https://reacttraining.com/react-router/web/guides/testing
    <MemoryRouter initialEntries={['/org/default?' + params]}>
      <Initialize/>
    </MemoryRouter>,
    { wrapper: UnstatedContainer } 
  )

  const userData = localStorage.getItem('voter-data')
  for (const val of Object.values(utmFields)) {
    expect(userData).toContain(val)
  }
})
Example #18
Source File: TestContainer.test.tsx    From antibody-web with MIT License 6 votes vote down vote up
describe("TestContainer", () => {
  const renderTestStep = async ({ step, api = {} }: { step: string, api?: object }) => {
    const [, context] = renderWithStubAppContext(
      <MemoryRouter initialEntries={[`/test/x`]}>
        <TestContainer step={step}>
          <div data-testid="render-check" />
        </TestContainer>
      </MemoryRouter>, api
    );
    await screen.findAllByTestId("render-check");

    return context;
  };

  it("Renders the content within the test container", async () => {
    await renderTestStep({ step: "x" });
    const content = await screen.findAllByTestId("render-check");
    expect(content.length).toBe(1);
  });

  it("Attempts to generate a new test record", async () => {
    const context = await renderTestStep({ step: "checkYourKit" });
    let generateTest = context.container.getTestApi().generateTest;
    expect(generateTest).toHaveBeenCalled();
  });

  it("Updates the test on the api", async () => {
    const context = await renderTestStep({ step: "checkYourKit" });
    let updateTest = context.container.getTestApi().updateTest;
    expect(updateTest).toHaveBeenCalledWith({ testRecord: { step: "checkYourKit", timerStartedAt: 10 } });
  });
});
Example #19
Source File: index.test.tsx    From oasis-wallet-web with Apache License 2.0 6 votes vote down vote up
renderComponent = (store: any) => {
  return render(
    <Provider store={store}>
      <MemoryRouter>
        <Navigation />
      </MemoryRouter>
    </Provider>,
  )
}
Example #20
Source File: Header.stories.tsx    From WEB_CodeSquare_AmongUs with MIT License 6 votes vote down vote up
Template: Story<HeaderProps> = (args) => (
  <MemoryRouter>
    <div
      css={css`
        padding: 8px;
        background: #c4c4c4;
      `}
    >
      <Header {...args} />
    </div>
  </MemoryRouter>
)
Example #21
Source File: index.stories.tsx    From pancake-toolkit with GNU General Public License v3.0 6 votes vote down vote up
WithSubmenuSelected: React.FC = () => {
  return (
    <MemoryRouter initialEntries={["/teams"]}>
      <Menu
        isDark={false}
        toggleTheme={noop}
        langs={langs}
        setLang={noop}
        currentLang="EN"
        cakePriceUsd={0.23158668932877668}
        links={links}
        subLinks={subLinks}
        footerLinks={footerLinks}
      >
        <div>
          <Heading as="h1" mb="8px">
            Submenu leaderboard selected
          </Heading>
        </div>
      </Menu>
    </MemoryRouter>
  );
}
Example #22
Source File: index.test.tsx    From react-boilerplate-cra-template with MIT License 6 votes vote down vote up
renderWithTheme = (theme?: DefaultTheme) => {
  return render(
    <MemoryRouter>
      <Link to="/test" theme={theme || themes.light}>
        HeaderLink
      </Link>
    </MemoryRouter>,
  );
}
Example #23
Source File: testHelpers.tsx    From knboard with MIT License 6 votes vote down vote up
renderWithProviders = (
  ui: React.ReactNode,
  initialState: RootState = rootInitialState
) => {
  const store = configureStore([thunk])(initialState);
  return {
    ...render(
      <MemoryRouter>
        <Provider store={store}>{ui}</Provider>
      </MemoryRouter>
    ),
    mockStore: store,
    getActionsTypes: () => store.getActions().map((a) => a.type),
  };
}
Example #24
Source File: index.stories.tsx    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
WithSubmenuSelected: React.FC = () => {
  return (
    <MemoryRouter initialEntries={["/teams"]}>
      <Menu
        isDark={false}
        toggleTheme={noop}
        langs={langs}
        setLang={noop}
        currentLang="EN"
        vvsPriceUsd={0.23158668932877668}
        links={links}
        subLinks={subLinks}
        footerLinks={footerLinks}
      >
        <div>
          <Heading as="h1" mb="8px">
            Submenu leaderboard selected
          </Heading>
        </div>
      </Menu>
    </MemoryRouter>
  );
}
Example #25
Source File: LinkTo.stories.tsx    From web3uikit with MIT License 6 votes vote down vote up
InternalLink.decorators = [
    (Story) => (
        <MemoryRouter>
            <Routes>
                <Route path="/" element={<Story />} />
                <Route
                    path="home"
                    element={
                        <LinkTo address="/" type="internal" text="Go Back" />
                    }
                />
            </Routes>
        </MemoryRouter>
    ),
];
Example #26
Source File: App.spec.tsx    From one-platform with MIT License 5 votes vote down vote up
it('renders the app', () => {
  const component = render(
    <MemoryRouter>
      <App />
    </MemoryRouter>
  );
  expect(component).toBeTruthy();
});
Example #27
Source File: router.tsx    From kinopub.webos with MIT License 5 votes vote down vote up
Router: React.FC<RouterProps> = (props) => {
  if (IS_WEB) {
    return <BrowserRouter {...props} />;
  }

  return <MemoryRouter {...props} />;
}
Example #28
Source File: Home.test.tsx    From ts-redux-react-realworld-example-app with MIT License 5 votes vote down vote up
it('Should change tabs', async () => {
  mockedGetFeed.mockResolvedValueOnce({
    articles: [{ ...defaultArticle, favorited: true }],
    articlesCount: 0,
  });
  mockedGetTags.mockResolvedValueOnce({ tags: ['the real tag'] });
  mockedUnfavoriteArticle.mockResolvedValueOnce({ ...defaultArticle, favorited: false });

  await act(async () => {
    store.dispatch(
      loadUser({
        email: '[email protected]',
        token: 'jwt.token.here',
        username: 'jake',
        bio: 'I work at statefarm',
        image: null,
      })
    );
    await render(
      <MemoryRouter>
        <Home />
      </MemoryRouter>
    );
  });

  mockedGetArticles.mockResolvedValueOnce({
    articles: [{ ...defaultArticle, favorited: true }],
    articlesCount: 0,
  });

  await act(async () => {
    fireEvent.click(screen.getByText('Global Feed'));
  });

  expect(store.getState().home.selectedTab).toMatch('Global Feed');

  mockedGetFeed.mockResolvedValueOnce({
    articles: [{ ...defaultArticle, favorited: true }],
    articlesCount: 0,
  });

  await act(async () => {
    fireEvent.click(screen.getByText('Your Feed'));
  });

  expect(store.getState().home.selectedTab).toMatch('Your Feed');

  mockedGetArticles.mockResolvedValueOnce({
    articles: [{ ...defaultArticle, favorited: true }],
    articlesCount: 0,
  });

  await act(async () => {
    fireEvent.click(screen.getByText('the real tag'));
  });

  expect(screen.getByText('# the real tag')).toHaveClass('active');
  expect(mockedGetArticles.mock.calls).toHaveLength(2);
  expect(mockedGetArticles.mock.calls[1][0]).toHaveProperty('tag', 'the real tag');
});