history#createMemoryHistory TypeScript Examples

The following examples show how to use history#createMemoryHistory. 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 fhir-validator-app with Apache License 2.0 7 votes vote down vote up
renderWithRouter = (
  ui: JSX.Element,
  { route = '/', history = createMemoryHistory({ initialEntries: [route] }) }: RenderOptions = {}
): RenderResult & { history: MemoryHistory } => {
  const Wrapper: FC = ({ children }) => <Router history={history}>{children}</Router>;
  return {
    ...render(ui, { wrapper: Wrapper }),
    history,
  };
}
Example #2
Source File: index.test.tsx    From oasis-wallet-web with Apache License 2.0 6 votes vote down vote up
describe('<AccountPage  />', () => {
  let store: ReturnType<typeof configureAppStore>

  beforeEach(() => {
    store = configureAppStore()
  })

  it.skip('should match snapshot', () => {
    const history = createMemoryHistory()
    history.push('/account/account_address')
    const page = renderPage(store, history)
    expect(page.container.firstChild).toMatchSnapshot()
  })
})
Example #3
Source File: ApplicationStoreProviderTestUtils.tsx    From legend-studio with Apache License 2.0 6 votes vote down vote up
TEST__provideMockedApplicationStore = <
  T extends LegendApplicationConfig,
>(
  config: T,
  pluginManager: LegendApplicationPluginManager,
  customization?: {
    mock?: ApplicationStore<T>;
    navigator?: WebApplicationNavigator;
  },
): ApplicationStore<T> => {
  const value =
    customization?.mock ??
    new ApplicationStore(
      config,
      customization?.navigator ??
        new WebApplicationNavigator(createMemoryHistory()),
      pluginManager,
    );
  const MockedApplicationStoreProvider = require('./ApplicationStoreProvider.js'); // eslint-disable-line @typescript-eslint/no-unsafe-assignment
  MockedApplicationStoreProvider.useApplicationStore = jest.fn();
  MockedApplicationStoreProvider.useApplicationStore.mockReturnValue(value);
  return value;
}
Example #4
Source File: testUtils.tsx    From rhub-app with MIT License 6 votes vote down vote up
connectedRender = (
  ui: ReactElement,
  state = {},
  route = '/',
  { ...renderOptions } = {}
) => {
  const store = mockStore(state);
  const history = createMemoryHistory({ initialEntries: [route] });
  const Wrapper = ({ children }: { children?: ReactNode }) => {
    return (
      <Provider store={store}>
        <Router history={history}>{children}</Router>
      </Provider>
    );
  };
  return {
    store,
    history,
    result: rtlRender(ui, { wrapper: Wrapper, ...renderOptions }),
  };
}
Example #5
Source File: main.test.tsx    From filecoin-CID-checker with Apache License 2.0 6 votes vote down vote up
describe('<Main /> spec', () => {
  it('renders the component', async () => {
    const history = createMemoryHistory()
    const { container, getByTestId } = render(
      <ThemeProvider theme={theme}>
        <Router history={history}>
          <Main />
        </Router>
      </ThemeProvider>,
    )

    expect(container.innerHTML).toMatch(/Search by Piece CID, Deal ID, or Miner ID/i)

    const loading = getByTestId('loading')
    expect(loading).toBeInTheDocument()
  })
})
Example #6
Source File: CollectionList.test.tsx    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
it('redirects to collection when clicking the collection list item', async () => {
  const history = createMemoryHistory({ initialEntries: ['/firestore/data'] });
  const { getByTestId } = await render(
    <Router history={history}>
      <Route path="/firestore/data">
        <CollectionListItem
          collectionId="sub-coll-1"
          routeMatchUrl="/coll-1/thing"
        />
      </Route>
    </Router>
  );

  fireEvent.click(getByTestId('firestore-collection-list-item'));
  expect(history.location.pathname).toBe('/coll-1/thing/sub-coll-1');
});
Example #7
Source File: layout.test.tsx    From filecoin-CID-checker with Apache License 2.0 6 votes vote down vote up
describe('<Header /> spec', () => {
  it('renders the component', async () => {
    const history = createMemoryHistory()

    const { container } = render(
      <ThemeProvider theme={theme}>
        <Router history={history}>
          <Header />
        </Router>
      </ThemeProvider>,
    )
    expect(container).toMatchSnapshot()
  })
})
Example #8
Source File: router.ts    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
getMockRouterProps = <Params extends { [K in keyof Params]: string } = {}>(path: string, params: Params): {
  history: MemoryHistory<LocationState>;
  location: Location<LocationState>;
  match: routerMatch<Params>
} => {
  const isExact = false;
  const url = generateUrl(path, params);

  const match: routerMatch<Params> = { isExact, path, url, params };
  const history = createMemoryHistory();
  const location = createLocation(match.url);

  return { history, location, match };
}
Example #9
Source File: TableRow.test.tsx    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
describe('RequestsTableRow', () => {
  it('redirects to corresponding request details path when clicking table row', async () => {
    const history = createMemoryHistory({
      initialEntries: ['/firestore/requests'],
    });
    const { getByRole } = render(
      <Router history={history}>
        <table>
          <RequestsTableRow
            request={FAKE_EVALUATION}
            requestId={FAKE_EVALUATION_ID}
            setShowCopyNotification={SET_SHOW_COPY_NOTIFICATION}
          />
        </table>
      </Router>
    );
    await act(async () => {
      fireEvent.click(getByRole('row'));
    });
    expect(history.location.pathname).toBe(
      `/firestore/requests/${FAKE_EVALUATION_ID}`
    );
  });
});
Example #10
Source File: index.test.tsx    From oasis-wallet-web with Apache License 2.0 6 votes vote down vote up
describe('<SearchAddress  />', () => {
  it('should match snapshot', () => {
    const component = render(<SearchAddress />)
    expect(component.container.firstChild).toMatchSnapshot()
  })

  it('should display an error on invalid address', async () => {
    const component = render(<SearchAddress />)
    const searchBar = await component.findByTestId('searchaddress')
    userEvent.type(searchBar, 'hello{enter}')
    const errorElem = screen.getByText('errors.invalidAddress')
    expect(errorElem).toBeInTheDocument()
  })

  it('should redirect to the account', async () => {
    const history = createMemoryHistory()
    const pushSpy = jest.spyOn(history, 'push')

    const component = render(
      <Router history={history}>
        <SearchAddress />
      </Router>,
    )

    const searchBar = await component.findByTestId('searchaddress')
    userEvent.type(searchBar, 'oasis1qz0k5q8vjqvu4s4nwxyj406ylnflkc4vrcjghuwk{enter}')
    expect(pushSpy).toHaveBeenCalledWith('/account/oasis1qz0k5q8vjqvu4s4nwxyj406ylnflkc4vrcjghuwk')
  })
})
Example #11
Source File: useBuckets.test.tsx    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
describe('useBuckets', () => {
  async function setup() {
    const history = createMemoryHistory({
      initialEntries: ['/storage/' + initialBucketName],
    });

    mockBuckets(buckets);
    const Wrapper: React.FC<React.PropsWithChildren<unknown>> = ({
      children,
    }) => {
      return (
        <Router history={history}>
          <Route exact path={storagePath + `:bucket/:path*`}>
            <TestStorageProvider>
              <Suspense fallback={'lol'}>{children}</Suspense>
            </TestStorageProvider>
          </Route>
        </Router>
      );
    };
    const { result } = renderHook(() => useBuckets(), {
      wrapper: Wrapper,
    });

    await waitFor(() => delay(100));

    return { buckets: result.current };
  }

  it('combines buckets from server and from URL', async () => {
    const { buckets } = await setup();
    expect(buckets).toEqual(['blinchik', 'pelmeni', initialBucketName]);
  });
});
Example #12
Source File: LoginProvider.test.tsx    From antibody-web with MIT License 6 votes vote down vote up
describe("<LoginProvider>", () => {
  it("Renders the contents correctly when the user has the login cookie set", () => {
    const cookieStub = { get: () => "yes" };
    const provider = render(
      <LoginProvider cookies={cookieStub}>
        <span data-testid="children-elements">Meow</span>
      </LoginProvider>
    );

    expect(provider.getAllByTestId("children-elements")).toHaveLength(1);
  });

  it("Redirects to / if the user is not logged in", () => {
    const cookieStub = { get: () => undefined };
    const historySpy = createMemoryHistory({
      initialEntries: ["/some-route-with-login"],
    });

    render(
      <Router history={historySpy}>
        <LoginProvider cookies={cookieStub}>
          <div />
        </LoginProvider>
      </Router>
    );

    expect(historySpy.location.pathname).toEqual("/");
  });
});
Example #13
Source File: index.test.tsx    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
describe('Storage Route', () => {
  it('displays the children', async () => {
    const history = createMemoryHistory({ initialEntries: ['/storage'] });

    const wrapperId = 'wrapper-id';
    const { findByTestId } = render(
      <FakeStorageWrappers fallbackTestId={'lol'}>
        <Router history={history}>
          <StorageRoute>
            <div data-testid={wrapperId} />
          </StorageRoute>
        </Router>
      </FakeStorageWrappers>
    );

    await findByTestId(wrapperId);
    expect(history.location.pathname).toMatch(/storage\/bucket.*/);
  });
});
Example #14
Source File: Results.test.tsx    From fhir-validator-app with Apache License 2.0 6 votes vote down vote up
describe('<Results />', () => {
  it('renders without crashing', () => {
    const history = createMemoryHistory();
    const results: ValidationResult = {
      outcome: {
        resourceType: 'OperationOutcome',
        issue: [],
      },
      profileUrls: [],
      resourceBlob: '',
      contentType: 'json',
    };
    history.push(RESULTS_PATH, { results });
    renderWithRouter(<Results />, { route: RESULTS_PATH, history });
  });
});
Example #15
Source File: Base.test.tsx    From mail-my-ballot with Apache License 2.0 6 votes vote down vote up
test('State Form Without Signature (Wisconsin) works', async () => {
  const history = createMemoryHistory()

  const register = mocked(client, true).register = jest.fn().mockResolvedValue({
    type: 'data',
    data: 'confirmationId',
  })
  mocked(client, true).fetchAnalytics = jest.fn().mockResolvedValue({})
  mocked(client, true).fetchContacts = jest.fn().mockResolvedValue([])

  const renderResult = render(
    <Router history={history}>
      <AddressContainer.Provider initialState={wisconsinAddress}>
        <ContactContainer.Provider initialState={wisconsinContact}>
          <Wisconsin/>
        </ContactContainer.Provider>
      </AddressContainer.Provider>
    </Router>,
    { wrapper: UnstatedContainer }
  )

  fillWithoutSigning(renderResult)

  await wait(
    () => expect(toPath(history.location.pathname, parseQS('')))
      .toEqual<SuccessPath>({id: "confirmationId", oid: "default", type: "success"})
  )
  await wait(() => expect(register).toHaveBeenCalledTimes(1))
})
Example #16
Source File: history-provider.ts    From malagu with MIT License 6 votes vote down vote up
constructor(
        @Value('malagu.react.history') protected readonly historyOptions: any
    ) {
        const historyCreatorMap: { [key: string]: any } = {
            hash: createHashHistory,
            browser: createBrowserHistory,
            memory: createMemoryHistory
        };
        if (this.historyOptions) {
            const { type, ...options } = historyOptions;
            const create = historyCreatorMap[type] || createHashHistory;
            this.history = create(options);
        } else {
            this.history = createHashHistory();
        }

    }
Example #17
Source File: kea-story.tsx    From posthog-foss with MIT License 6 votes vote down vote up
function resetKeaWithState(state: Record<string, any>): void {
    const history = createMemoryHistory({ initialEntries: [state.kea.router.location] })
    ;(history as any).pushState = history.push
    ;(history as any).replaceState = history.replace
    initKea({ state, routerLocation: history.location, routerHistory: history })
    featureFlagLogic.mount()
    systemStatusLogic.mount()
    router.mount()
    const { store } = getContext()
    store.dispatch({ type: 'bla' })
}
Example #18
Source File: issue-24.test.tsx    From rocon with MIT License 6 votes vote down vote up
it("use of navigate in useEffect", () => {
  // https://github.com/uhyo/rocon/issues/24
  const history = createMemoryHistory({
    initialEntries: [
      {
        pathname: "/about",
        state: null,
      },
    ],
  });
  renderInHistory(history, <App />);
  // useEffect should navigate to the root
  expect(history.location).toMatchObject({
    pathname: "/",
    state: null,
  });
  expect(screen.queryByText("The root page")).toBeInTheDocument();
});
Example #19
Source File: testUtils.tsx    From twilio-voice-notification-app with Apache License 2.0 6 votes vote down vote up
renderWithAppContexts = (
  ui: React.ReactElement,
  options?: any
) => {
  const history = createMemoryHistory();
  const Wrapper = makeContextWrapper(history);
  return {
    ...render(ui, { wrapper: Wrapper, ...options }),
    history,
  };
}
Example #20
Source File: survey-result.spec.ts    From clean-react with GNU General Public License v3.0 6 votes vote down vote up
makeSut = ({ loadSurveyResultSpy = new LoadSurveyResultSpy(), saveSurveyResultSpy = new SaveSurveyResultSpy(), initialState = null }: SutParams = {}): SutTypes => {
  const history = createMemoryHistory({ initialEntries: ['/', '/surveys/any_id'], initialIndex: 1 })
  const { setCurrentAccountMock } = renderWithHistory({
    history,
    Page: () => SurveyResult({ loadSurveyResult: loadSurveyResultSpy, saveSurveyResult: saveSurveyResultSpy }),
    states: initialState ? [{ atom: surveyResultState, value: initialState }] : []
  })
  return {
    loadSurveyResultSpy,
    saveSurveyResultSpy,
    history,
    setCurrentAccountMock
  }
}
Example #21
Source File: init.ts    From posthog-foss with MIT License 6 votes vote down vote up
export function initKeaTests(): void {
    window.POSTHOG_APP_CONTEXT = {
        current_team: MOCK_DEFAULT_TEAM,
        ...window.POSTHOG_APP_CONTEXT,
    } as unknown as AppContext
    posthog.init('no token', {
        api_host: 'borked',
        test: true,
        autocapture: false,
        disable_session_recording: true,
        advanced_disable_decide: true,
        opt_out_capturing_by_default: true,
        loaded: (p) => {
            p.opt_out_capturing()
        },
    })

    const history = createMemoryHistory()
    ;(history as any).pushState = history.push
    ;(history as any).replaceState = history.replace
    initKea({ beforePlugins: [testUtilsPlugin], routerLocation: history.location, routerHistory: history })
}
Example #22
Source File: routesTest.tsx    From devex with GNU General Public License v3.0 6 votes vote down vote up
describe('react router test', () => {
  const history = createMemoryHistory()

  it('renders layout', () => {
    const homePage = shallow(
      <Router history={history}>
        <Layout />
      </Router>
    )
    expect(homePage.find(Layout)).toHaveLength(1)
  })

  it('renders a spinner when in network transition', () => {
    const homePage = mount(
      <Router history={history}>
        <NetworkContext.Provider value={{
          isValidUrl: null,
          isIsolatedServer: true,
          dataService: null,
          networkUrl: '',
          inTransition: true,
          isLoadingNetworks: true
        }}>
        <App />
        </NetworkContext.Provider>
      </Router>
    )

    expect(homePage.find(Spinner)).toHaveLength(1)
  })
  
})
Example #23
Source File: survey-list.spec.ts    From clean-react with GNU General Public License v3.0 6 votes vote down vote up
makeSut = (loadSurveyListSpy = new LoadSurveyListSpy()): SutTypes => {
  const history = createMemoryHistory({ initialEntries: ['/'] })
  const { setCurrentAccountMock } = renderWithHistory({
    history,
    Page: () => SurveyList({ loadSurveyList: loadSurveyListSpy })
  })
  return {
    loadSurveyListSpy,
    history,
    setCurrentAccountMock
  }
}
Example #24
Source File: Invitation.test.tsx    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
describe("Invitation", () => {
  it("Invitation", async () => {
    // MOCK ROUTER https://testing-library.com/docs/example-react-router
    const history = createMemoryHistory();

    const { getByText, queryByTestId } = renderWithStyledTheme(
      <MockedProvider mocks={mocks} addTypename={false}>
        <Router history={history}>
          <AuthProvider>
            <NotificationsWithPortal />
            <Invitation />
          </AuthProvider>
        </Router>
      </MockedProvider>
    );

    history.push("/invitation/" + FAKE_TOKEN);
    expect(queryByTestId("loading")).toBeInTheDocument();
    await wait(0);
    expect(queryByTestId("loading")).not.toBeInTheDocument();
    expect(getByText("AmazingRoom")).toBeInTheDocument();
    expect(getByText(/Anurag Hazra/i)).toBeInTheDocument();
    expect(getByText(/Accept Invitation/i)).toBeInTheDocument();
    expect(history.location.pathname).toBe("/invitation/" + FAKE_TOKEN);

    // ACCEPT
    let button = getByText(/Accept Invitation/i);

    await act(async () => fireEvent.click(button));
    await wait(0);

    // CHECK redirection
    expect(history.location.pathname).toBe("/");
  });
});
Example #25
Source File: index.tsx    From react-resource-router with Apache License 2.0 6 votes vote down vote up
MemoryRouter = (props: MemoryRouterProps) => {
  const { location, children } = props;
  const config: MemoryHistoryBuildOptions = {};

  if (location) {
    config.initialEntries = [location];
  }

  const history = createMemoryHistory(config);
  const routerProps = getRouterProps(props);

  return (
    // @ts-ignore suppress history will be overwritten warning
    <Router history={history} {...(routerProps as RouterProps)}>
      {children}
    </Router>
  );
}
Example #26
Source File: signup.spec.ts    From clean-react with GNU General Public License v3.0 5 votes vote down vote up
history = createMemoryHistory({ initialEntries: ['/signup'] })
Example #27
Source File: index.test.tsx    From oasis-wallet-web with Apache License 2.0 5 votes vote down vote up
history = createMemoryHistory()
Example #28
Source File: header.spec.ts    From clean-react with GNU General Public License v3.0 5 votes vote down vote up
makeSut = (account = mockAccountModel()): SutTypes => {
  const history = createMemoryHistory({ initialEntries: ['/'] })
  const { setCurrentAccountMock } = renderWithHistory({ history, Page: Header, account })
  return {
    history,
    setCurrentAccountMock
  }
}
Example #29
Source File: useBucket.test.tsx    From firebase-tools-ui with Apache License 2.0 5 votes vote down vote up
describe('useBucket', () => {
  function setup() {
    const history = createMemoryHistory({
      initialEntries: ['/storage/' + initialBucketName],
    });

    const Wrapper: React.FC<React.PropsWithChildren<unknown>> = ({
      children,
    }) => {
      return (
        <Router history={history}>
          <Route exact path={storagePath + `:bucket/:path*`}>
            {children}
          </Route>
        </Router>
      );
    };
    const { result } = renderHook(() => useBucket(), { wrapper: Wrapper });

    const [bucket, setBucket] = result.current;
    return {
      bucket,
      setBucket,
      history,
    };
  }

  it('picks up bucket name from the URL', async () => {
    const { bucket } = setup();
    expect(bucket).toBe(initialBucketName);
  });

  it('updates the URL', async () => {
    const newBucketName = 'lol';

    const { setBucket, history } = setup();
    act(() => {
      setBucket(newBucketName);
    });
    expect(history.location.pathname).toBe('/storage/' + newBucketName);
  });
});