use-formatter.spec.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { renderHook } from '@testing-library/react';
  2. import { useFormatter } from './use-formatter';
  3. const mocks = vi.hoisted(() => {
  4. return {
  5. useCurrentPagePathMock: vi.fn<() => string | undefined>(() => undefined),
  6. };
  7. });
  8. vi.mock('~/states/page', () => {
  9. return { useCurrentPagePath: mocks.useCurrentPagePathMock };
  10. });
  11. describe('useFormatter', () => {
  12. describe('format()', () => {
  13. it('returns an empty string when the argument is undefined', () => {
  14. // setup
  15. const mastacheMock = {
  16. render: vi.fn(),
  17. };
  18. vi.doMock('mustache', () => mastacheMock);
  19. // when
  20. const { result } = renderHook(() => useFormatter());
  21. const { format } = result.current;
  22. // call with undefined
  23. const markdown = format(undefined);
  24. // then
  25. expect(markdown).toBe('');
  26. expect(mastacheMock.render).not.toHaveBeenCalled();
  27. });
  28. });
  29. it('returns markdown as-is when mustache.render throws an error', () => {
  30. // setup
  31. const mastacheMock = {
  32. render: vi.fn(() => {
  33. throw new Error();
  34. }),
  35. };
  36. vi.doMock('mustache', () => mastacheMock);
  37. // when
  38. const { result } = renderHook(() => useFormatter());
  39. const { format } = result.current;
  40. const markdown = 'markdown body';
  41. const formatted = format(markdown);
  42. // then
  43. expect(formatted).toBe('markdown body');
  44. });
  45. it('returns markdown formatted when currentPagePath is undefined', () => {
  46. // when
  47. const { result } = renderHook(() => useFormatter());
  48. const { format } = result.current;
  49. const markdown = `
  50. title: {{{title}}}{{^title}}(empty){{/title}}
  51. path: {{{path}}}
  52. `;
  53. const formatted = format(markdown);
  54. // then
  55. expect(formatted).toBe(`
  56. title: (empty)
  57. path: /
  58. `);
  59. });
  60. it('returns markdown formatted', () => {
  61. // setup
  62. mocks.useCurrentPagePathMock.mockReturnValue('/Sandbox');
  63. // 2023/5/31 15:01:xx
  64. vi.setSystemTime(new Date(2023, 4, 31, 15, 1));
  65. // when
  66. const { result } = renderHook(() => useFormatter());
  67. const { format } = result.current;
  68. const markdown = `
  69. title: {{{title}}}
  70. path: {{{path}}}
  71. date: {{yyyy}}/{{MM}}/{{dd}} {{HH}}:{{mm}}
  72. `;
  73. const formatted = format(markdown);
  74. // then
  75. expect(formatted).toBe(`
  76. title: Sandbox
  77. path: /Sandbox
  78. date: 2023/05/31 15:01
  79. `);
  80. });
  81. });