Skip to content
This repository has been archived by the owner on Sep 24, 2021. It is now read-only.

Commit

Permalink
add test
Browse files Browse the repository at this point in the history
  • Loading branch information
yuki-takei committed Apr 23, 2019
1 parent 8ad8e43 commit 8c52b33
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/plugin/util/custom-tag-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
42 changes: 42 additions & 0 deletions src/test/plugin/util/custom-tag-utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: '/',
},
});
});


});

0 comments on commit 8c52b33

Please sign in to comment.