In addition to checking the structural and syntactic correctness of your Twig template files using them, you can also unit test the logic of your Twig templates.
For example, you can check the correct behavior of the if-elseif-else-endif , and you can do it in isolation, that is, without having to go through controllers with all their dependencies.
Take a look at https://github.com/journeymonitor/control/blob/2645c69/src/AppBundle/Resources/views/testcases/_testresults-overview-testresult-label.html.twig . This is a very simple template, but it has a number of actions - depending on the value of testresult.exitCode , different label names should be displayed.
At https://github.com/journeymonitor/control/blob/bc42e78/tests/AppBundle/Resources/views/testcases/_testresults-overview-testresult-label.html.twig.test.php you can see a unit test case for this template.
In the test example, a new Twig_Environment is created that allows you to load the Twig template file and render it with different Testresult objects passed as a parameter. The result of the rendering operation can then be claimed, as in any other PHPUnit test:
$loader = new Twig_Loader_Filesystem(__DIR__ . '/../../../../../src/AppBundle/Resources/views/testcases/'); $twig = new Twig_Environment($loader, array( 'cache' => '/var/tmp/journeymonitor-twig-tests-cache', )); $template = $twig->loadTemplate('_testresults-overview-testresult-label.html.twig'); $testresult = new \AppBundle\Entity\Testresult(); $testresult->setExitCode(0); $this->assertSame('success', $template->render(['testresult' => $testresult]));
Pay attention to shell commands on lines 8 and 9 - the Twig environment caches its template files, and in order to have reliable tests, you need to make sure that the cache location has been wiped before each run:
`rm -rf /var/tmp/journeymonitor-twig-tests-cache`; `mkdir -p /var/tmp/journeymonitor-twig-tests-cache`;
source share