useRoutes.spec.tsx 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import {createMemoryHistory, Route, Router, RouterContext} from 'react-router';
  2. import {render} from 'sentry-test/reactTestingLibrary';
  3. import {useRoutes} from 'sentry/utils/useRoutes';
  4. import {RouteContext} from 'sentry/views/routeContext';
  5. describe('useRoutes', () => {
  6. it('returns the current routes object', function () {
  7. let routes;
  8. function HomePage() {
  9. routes = useRoutes();
  10. return null;
  11. }
  12. const memoryHistory = createMemoryHistory();
  13. memoryHistory.push('/');
  14. render(
  15. <Router
  16. history={memoryHistory}
  17. render={props => {
  18. return (
  19. <RouteContext.Provider value={props}>
  20. <RouterContext {...props} />
  21. </RouteContext.Provider>
  22. );
  23. }}
  24. >
  25. <Route path="/" component={HomePage} />
  26. </Router>
  27. );
  28. expect(routes.length).toEqual(1);
  29. expect(routes[0]).toEqual({path: '/', component: HomePage});
  30. });
  31. it('throws error when called outside of routes provider', function () {
  32. // Error is expected, do not fail when calling console.error
  33. jest.spyOn(console, 'error').mockImplementation();
  34. const memoryHistory = createMemoryHistory();
  35. memoryHistory.push('/');
  36. expect(() =>
  37. render(
  38. <RouteContext.Provider value={null}>
  39. <Router history={memoryHistory}>
  40. <Route
  41. path="/"
  42. component={() => {
  43. useRoutes();
  44. return null;
  45. }}
  46. />
  47. </Router>
  48. </RouteContext.Provider>
  49. )
  50. ).toThrow(/useRouteContext called outside of routes provider/);
  51. });
  52. });