use-formatter.spec.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import type { ITemplate } from '@growi/core/dist/interfaces/template';
  2. import { mock } from 'vitest-mock-extended';
  3. import { useFormatter } from './use-formatter';
  4. const mocks = vi.hoisted(() => {
  5. return {
  6. useCurrentPagePathMock: vi.fn(() => { return {} }),
  7. };
  8. });
  9. vi.mock('~/stores/page', () => {
  10. return { useCurrentPagePath: mocks.useCurrentPagePathMock };
  11. });
  12. describe('useFormatter', () => {
  13. describe('format()', () => {
  14. it('returns an empty string when the argument is undefined', () => {
  15. // setup
  16. const mastacheMock = {
  17. render: vi.fn(),
  18. };
  19. vi.doMock('mustache', () => mastacheMock);
  20. // when
  21. const { format } = useFormatter();
  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(() => { throw new Error() }),
  33. };
  34. vi.doMock('mustache', () => mastacheMock);
  35. // when
  36. const { format } = useFormatter();
  37. const template = mock<ITemplate>();
  38. template.markdown = 'markdown body';
  39. const markdown = format(template);
  40. // then
  41. expect(markdown).toBe('markdown body');
  42. });
  43. it('returns markdown formatted when currentPagePath is undefined', () => {
  44. // when
  45. const { format } = useFormatter();
  46. const template = mock<ITemplate>();
  47. template.markdown = `
  48. title: {{{title}}}{{^title}}(empty){{/title}}
  49. path: {{{path}}}
  50. `;
  51. const markdown = format(template);
  52. // then
  53. expect(markdown).toBe(`
  54. title: (empty)
  55. path: /
  56. `);
  57. });
  58. it('returns markdown formatted', () => {
  59. // setup
  60. mocks.useCurrentPagePathMock.mockImplementation(() => {
  61. return { data: '/Sandbox' };
  62. });
  63. // 2023/5/31 15:01:xx
  64. vi.setSystemTime(new Date(2023, 4, 31, 15, 1));
  65. // when
  66. const { format } = useFormatter();
  67. const template = mock<ITemplate>();
  68. template.markdown = `
  69. title: {{{title}}}
  70. path: {{{path}}}
  71. date: {{yyyy}}/{{MM}}/{{dd}} {{HH}}:{{mm}}
  72. `;
  73. const markdown = format(template);
  74. // then
  75. expect(markdown).toBe(`
  76. title: Sandbox
  77. path: /Sandbox
  78. date: 2023/05/31 15:01
  79. `);
  80. });
  81. });