use-formatter.spec.tsx 2.0 KB

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