rob-revisited/ide/ui/js/twig-preview.test.mjs

53 lines
2.5 KiB
JavaScript

// node --test ide/ui/js/twig-preview.test.mjs
import test from 'node:test';
import assert from 'node:assert/strict';
import { composeTwig, linkProjectCss, twigPreviewText, blocksOf } from './twig-preview.js';
const files = {
'templates/base.html.twig': `<!DOCTYPE html><html><head><title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}{% endblock %}{% block javascripts %}{{ importmap('app') }}{% endblock %}</head>
<body>{% block body %}{% endblock %}{% include 'footer.html.twig' %}</body></html>`,
'templates/footer.html.twig': '<footer>FOOT</footer>',
'assets/styles/app.css': 'body { color: red }',
'assets/extra.css': 'p {}',
};
const read = async (p) => (p in files ? files[p] : null);
const child = `{% extends 'base.html.twig' %}
{% block title %}Hello {{ controller_name }}{% endblock %}
{% block stylesheets %}{{ parent() }}<link rel="stylesheet" href="{{ asset('extra.css') }}">{% endblock %}
{% block body %}<h1>Hi</h1>{% endblock %}`;
test('blocks are read with their names', () => {
assert.deepEqual(Object.keys(blocksOf(child)).sort(), ['body', 'stylesheets', 'title']);
});
test('extends brings the parent with the child blocks and the includes', async () => {
const page = await composeTwig('templates/home/index.html.twig', child, read);
assert.match(page, /<title>Hello \{\{ controller_name \}\}<\/title>/);
assert.match(page, /<body><h1>Hi<\/h1><footer>FOOT<\/footer><\/body>/);
assert.doesNotMatch(page, /Welcome!/);
});
test('the project css is linked: asset() and importmap', async () => {
const out = await twigPreviewText('templates/home/index.html.twig', child, read, true);
assert.match(out, /href="\/assets\/extra.css"/);
assert.match(out, /<link rel="stylesheet" href="\/assets\/styles\/app.css"><\/head>/);
assert.doesNotMatch(out, /\{%|\{\{/);
});
test('function calls are not shown as text', async () => {
const out = await twigPreviewText('templates/home/index.html.twig', child, read, true);
assert.doesNotMatch(out, /importmap|parent\(\)/);
const { stripTwig } = await import('./twig-preview.js');
assert.equal(stripTwig('<a href="{{ path(\'home\') }}">{{ user.name|upper }}</a>{{ form(f) }}'), '<a href="#">user.name</a>');
});
test('off: the template alone, its tags out', async () => {
const out = await twigPreviewText('templates/home/index.html.twig', child, read, false);
assert.doesNotMatch(out, /FOOT|<html/);
assert.match(out, /<h1>Hi<\/h1>/);
});
test('a missing parent keeps the template as it is', async () => {
assert.equal(await linkProjectCss('<p>x</p>', read), '<p>x</p>');
});