useUrlParams.spec.tsx 2.5 KB

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