import { marked } from '../../src/marked.js';
import { timeout } from './utils.js';
describe('Hooks', () => {
it('should preprocess markdown', () => {
marked.use({
hooks: {
preprocess(markdown) {
return `# preprocess\n\n${markdown}`;
}
}
});
const html = marked('*text*');
expect(html.trim()).toBe('
preprocess
\ntext
');
});
it('should preprocess async', async() => {
marked.use({
async: true,
hooks: {
async preprocess(markdown) {
await timeout();
return `# preprocess async\n\n${markdown}`;
}
}
});
const promise = marked('*text*');
expect(promise).toBeInstanceOf(Promise);
const html = await promise;
expect(html.trim()).toBe('preprocess async
\ntext
');
});
it('should preprocess options', () => {
marked.use({
hooks: {
preprocess(markdown) {
this.options.breaks = true;
return markdown;
}
}
});
const html = marked('line1\nline2');
expect(html.trim()).toBe('line1
line2
');
});
it('should preprocess options async', async() => {
marked.use({
async: true,
hooks: {
async preprocess(markdown) {
await timeout();
this.options.breaks = true;
return markdown;
}
}
});
const html = await marked('line1\nline2');
expect(html.trim()).toBe('line1
line2
');
});
it('should postprocess html', () => {
marked.use({
hooks: {
postprocess(html) {
return html + 'postprocess
';
}
}
});
const html = marked('*text*');
expect(html.trim()).toBe('text
\npostprocess
');
});
it('should postprocess async', async() => {
marked.use({
async: true,
hooks: {
async postprocess(html) {
await timeout();
return html + 'postprocess async
\n';
}
}
});
const promise = marked('*text*');
expect(promise).toBeInstanceOf(Promise);
const html = await promise;
expect(html.trim()).toBe('text
\npostprocess async
');
});
it('should process all hooks in reverse', async() => {
marked.use({
hooks: {
preprocess(markdown) {
return `# preprocess1\n\n${markdown}`;
},
postprocess(html) {
return html + 'postprocess1
\n';
}
}
});
marked.use({
async: true,
hooks: {
preprocess(markdown) {
return `# preprocess2\n\n${markdown}`;
},
async postprocess(html) {
await timeout();
return html + 'postprocess2 async
\n';
}
}
});
const promise = marked('*text*');
expect(promise).toBeInstanceOf(Promise);
const html = await promise;
expect(html.trim()).toBe('preprocess1
\npreprocess2
\ntext
\npostprocess2 async
\npostprocess1
');
});
});