From 8c52b335e5bfbd84b8338e1241b05f74fd34a4d6 Mon Sep 17 00:00:00 2001 From: Yuki Takei Date: Tue, 23 Apr 2019 21:57:29 +0900 Subject: [PATCH] add test --- src/plugin/util/custom-tag-utils.js | 10 ++++- src/test/plugin/util/custom-tag-utils.test.js | 42 +++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/plugin/util/custom-tag-utils.js b/src/plugin/util/custom-tag-utils.js index 0f71c37..edf7219 100644 --- a/src/plugin/util/custom-tag-utils.js +++ b/src/plugin/util/custom-tag-utils.js @@ -22,11 +22,17 @@ function createRandomStr(length) { * @return {{html: string, tagContextMap: Object.}} */ 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(); diff --git a/src/test/plugin/util/custom-tag-utils.test.js b/src/test/plugin/util/custom-tag-utils.test.js index a4ff685..7c630a2 100644 --- a/src/test/plugin/util/custom-tag-utils.test.js +++ b/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 = '

header

\n$ls(/)
'; + + const result = customTagUtils.findTagAndReplace(tagPattern, html); + + expect(result.html).toMatch(/

header<\/h1>\n
<\/div>/); + expect(result.tagContextMap).toEqual({ + 'ls-dummyDomId': { + tagExpression: '$ls(/)', + method: 'ls', + args: '/', + }, + }); + }); + + });