Yuki Takei 7 jaren geleden
bovenliggende
commit
a5b915a97e

+ 8 - 2
packages/growi-commons/src/plugin/util/custom-tag-utils.js

@@ -22,11 +22,17 @@ function createRandomStr(length) {
  * @return {{html: string, tagContextMap: Object.<string, TagContext>}}
  */
 function findTagAndReplace(tagPattern, html, replace) {
+  let replacedHtml = html;
+  const tagContextMap = {};
+
+  if (tagPattern == null || html == null) {
+    return { html: replacedHtml, tagContextMap };
+  }
+
   // see: https://regex101.com/r/NQq3s9/9
   const pattern = new RegExp(`\\$(${tagPattern.source})\\((.*?)\\)(?=[<\\[\\s\\$])|\\$(${tagPattern.source})\\((.*)\\)(?![<\\[\\s\\$])`, 'g');
 
-  const tagContextMap = {};
-  const replacedHtml = html.replace(pattern, (all, group1, group2, group3, group4) => {
+  replacedHtml = html.replace(pattern, (all, group1, group2, group3, group4) => {
     const tagExpression = all;
     const method = (group1 || group3).trim();
     const args = (group2 || group4 || '').trim();

+ 42 - 0
packages/growi-commons/src/test/plugin/util/custom-tag-utils.test.js

@@ -25,4 +25,46 @@ describe('customTagUtils', () => {
     expect(createRandomStr(10)).toMatch(/^[a-z0-9]{10}$/);
   });
 
+  test('.findTagAndReplace() returns default object when tagPattern is null', () => {
+    const htmlMock = jest.fn();
+    htmlMock.replace = jest.fn();
+
+    const result = customTagUtils.findTagAndReplace(null, '');
+
+    expect(result).toEqual({ html: '', tagContextMap: {} });
+    expect(htmlMock.replace).not.toHaveBeenCalled();
+  });
+
+  test('.findTagAndReplace() returns default object when html is null', () => {
+    const tagPatternMock = jest.fn();
+    tagPatternMock.source = jest.fn();
+
+    const result = customTagUtils.findTagAndReplace(tagPatternMock, null);
+
+    expect(result).toEqual({ html: null, tagContextMap: {} });
+    expect(tagPatternMock.source).not.toHaveBeenCalled();
+  });
+
+  test('.findTagAndReplace() works correctly', () => {
+    // setup mocks for private function
+    customTagUtils.__Rewire__('createRandomStr', (length) => {
+      return 'dummyDomId';
+    });
+
+    const tagPattern = /ls|lsx/;
+    const html = '<section><h1>header</h1>\n$ls(/)</section>';
+
+    const result = customTagUtils.findTagAndReplace(tagPattern, html);
+
+    expect(result.html).toMatch(/<section><h1>header<\/h1>\n<div id="ls-dummyDomId"><\/div>/);
+    expect(result.tagContextMap).toEqual({
+      'ls-dummyDomId': {
+        tagExpression: '$ls(/)',
+        method: 'ls',
+        args: '/',
+      },
+    });
+  });
+
+
 });