Add test for highlightCode html modifier

This commit is contained in:
Samy Pessé
2016-04-27 15:42:55 +02:00
parent d68dc82159
commit 999882e723
4 changed files with 110 additions and 2 deletions
@@ -0,0 +1,63 @@
jest.autoMockOff();
var cheerio = require('cheerio');
var Promise = require('../../../utils/promise');
describe('highlightCode', function() {
var highlightCode = require('../highlightCode');
function doHighlight(lang, code) {
return {
text: '' + (lang || '') + '$' + code
};
}
function doHighlightAsync(lang, code) {
return Promise()
.then(function() {
return doHighlight(lang, code);
});
}
pit('should call it for normal code element', function() {
var $ = cheerio.load('<p>This is a <code>test</code></p>');
return highlightCode(doHighlight, $)
.then(function() {
var $code = $('code');
expect($code.text()).toBe('$test');
});
});
pit('should call it for markdown code block', function() {
var $ = cheerio.load('<pre><code class="lang-js">test</code></pre>');
return highlightCode(doHighlight, $)
.then(function() {
var $code = $('code');
expect($code.text()).toBe('js$test');
});
});
pit('should call it for asciidoc code block', function() {
var $ = cheerio.load('<pre><code class="language-python">test</code></pre>');
return highlightCode(doHighlight, $)
.then(function() {
var $code = $('code');
expect($code.text()).toBe('python$test');
});
});
pit('should accept async highlighter', function() {
var $ = cheerio.load('<pre><code class="language-python">test</code></pre>');
return highlightCode(doHighlightAsync, $)
.then(function() {
var $code = $('code');
expect($code.text()).toBe('python$test');
});
});
});
+1 -1
View File
@@ -8,7 +8,7 @@ function editHTMLElement($, selector, fn) {
return Promise.forEach($elements, function(el) {
var $el = $(el);
fn($el);
return fn($el);
});
}
+44
View File
@@ -0,0 +1,44 @@
var Promise = require('../../utils/promise');
var editHTMLElement = require('./editHTMLElement');
/**
Highlight all code elements
@param {Function(lang, body) -> String} highlight
@param {HTMLDom} $
@return {Promise}
*/
function highlightCode(highlight, $) {
return editHTMLElement($, 'code', function($code) {
var classNames = ($code.attr('class') || '').split(' ');
var lang = classNames
.map(function(cl) {
// Markdown
if (cl.search('lang-') === 0) {
return cl.slice('lang-'.length);
}
// Asciidoc
if (cl.search('language-') === 0) {
return cl.slice('language-'.length);
}
return null;
})
.find(function(cl) {
return Boolean(cl);
});
var source = $code.text();
return Promise(highlight(lang, source))
.then(function(r) {
if (r.html) {
$code.html(r.html);
} else {
$code.text(r.text);
}
});
});
}
module.exports = highlightCode;
+2 -1
View File
@@ -9,5 +9,6 @@ module.exports = {
fetchRemoteImages: require('./fetchRemoteImages'),
svgToPng: require('./svgToPng'),
resolveLinks: require('./resolveLinks'),
annotateText: require('./annotateText')
annotateText: require('./annotateText'),
highlightCode: require('./highlightCode')
};