useUrlParams.spec.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import {browserHistory} from 'react-router';
  2. import type {Location} from 'history';
  3. import {reactHooks} from 'sentry-test/reactTestingLibrary';
  4. import {useLocation} from 'sentry/utils/useLocation';
  5. import useUrlParams from './useUrlParams';
  6. jest.mock('react-router');
  7. jest.mock('sentry/utils/useLocation');
  8. const mockUseLocation = useLocation as jest.MockedFunction<typeof useLocation>;
  9. const mockBrowserHistoryPush = browserHistory.push as jest.MockedFunction<
  10. typeof browserHistory.push
  11. >;
  12. type Query = {limit: string; page: string};
  13. describe('useUrlParams', () => {
  14. beforeEach(() => {
  15. mockBrowserHistoryPush.mockReset();
  16. mockUseLocation.mockReturnValue({
  17. query: {
  18. page: '3',
  19. limit: '50',
  20. },
  21. } as Location<Query>);
  22. });
  23. it('should read query values from the url', () => {
  24. const {result} = reactHooks.renderHook(() => useUrlParams());
  25. expect(result.current.getParamValue('page')).toBe('3');
  26. expect(result.current.getParamValue('limit')).toBe('50');
  27. });
  28. it('should read a specific query value if the defaultKey is passed along', () => {
  29. const {result} = reactHooks.renderHook(() => useUrlParams('page'));
  30. expect(result.current.getParamValue()).toBe('3');
  31. });
  32. it('should read the default value for the defaultKey', () => {
  33. const {result} = reactHooks.renderHook(() => useUrlParams('foo', 'bar'));
  34. expect(result.current.getParamValue()).toBe('bar');
  35. });
  36. it('should update browser history with new values', () => {
  37. const {result} = reactHooks.renderHook(() => useUrlParams());
  38. result.current.setParamValue('page', '4');
  39. expect(browserHistory.push).toHaveBeenCalledWith({
  40. query: {
  41. page: '4',
  42. limit: '50',
  43. },
  44. });
  45. });
  46. it('should update browser history with new values for the defaultKey', () => {
  47. const {result} = reactHooks.renderHook(() => useUrlParams('page'));
  48. result.current.setParamValue('4');
  49. expect(browserHistory.push).toHaveBeenCalledWith({
  50. query: {
  51. page: '4',
  52. limit: '50',
  53. },
  54. });
  55. });
  56. it('uses the same function reference after each render', () => {
  57. const {result, rerender} = reactHooks.renderHook(() => useUrlParams());
  58. const firstResult = result.current;
  59. rerender();
  60. const secondResult = result.current;
  61. expect(firstResult.getParamValue).toBe(secondResult.getParamValue);
  62. expect(firstResult.setParamValue).toBe(secondResult.setParamValue);
  63. });
  64. });