Creating a unit test for a Twig template
Published on 2021-07-02 • Modified on 2021-07-02
In this snippet, we see how to create a unit test for a Twig template. This template contains a simple if
tag like this:
{% if case == 1 %}This is case 1! 🎉{% else %}This is NOT case 1.{% endif %}
We use a test provider; the two first cases are the nominal cases, the third one checks that an exception is raised because the case
variable isn't passed to the template. We have an error when using the Twig strict mode that is enabled with the strict_variables
parameter.
<?php
declare(strict_types=1);
namespace App\Tests\Integration\Twig;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Twig\Environment;
use Twig\Error\RuntimeError;
final class Snippet152Test extends KernelTestCase
{
private Environment $twig;
protected function setUp(): void
{
$this->twig = self::getContainer()->get(Environment::class);
}
/**
* @return iterable<string, array{0: array<string,mixed>, 1: string, 2: bool}>
*/
public function snippet1527Provider(): iterable
{
yield 'case 1, nomimal case' => [['case' => 1], 'this is case 1', false];
yield 'case 2, nomimal case' => [['case' => 2], 'this is NOT case 1', false];
yield 'case 3, wrong type' => [['case' => 'c'], 'this is NOT case 1', false]; // no strict type at the Twig level
yield 'exception case' => [['case_not_provided' => 99], 'RuntimeError!', true];
}
/**
* @param array<string, mixed> $context
*
* @dataProvider snippet1527Provider
*/
public function testSnippet152(array $context, string $needle, bool $expectException): void
{
if ($expectException) {
$this->expectException(RuntimeError::class);
}
$haystack = $this->twig->render('snippet/code/_152_demo.html.twig', $context);
self::assertStringContainsStringIgnoringCase($needle, $haystack);
}
}
HTML demo of the snippet
This is case 1! 🎉
More on Stackoverflow Read the doc Random snippet