Symfony provides custom assertions to simplify your tests. They are optional, but we recommend to use them to make your tests easier to maintain. For example:
1 2 3 4 5 6 7 8
// with default PHPUnit assertions
$this->assertSame(
'This is not a valid coupon code.',
trim($crawler->filter('#errorMessages')->text())
);
// with custom Symfony assertions
$this->assertSelectorTextContains('#errorMessages', 'This is not a valid coupon code.');
In Symfony 6.4 we're introducing new custom assertions.
Any Selector Assertions
Consider the following HTML code:
1 2 3 4 5
<ul>
<li>test 1</li>
<li>test 2</li>
<li>test 3</li>
</ul>
If you need to test that any of the <li>
items contains the text test 3
,
you need to loop over all <li>
elements or extract all their contents:
1 2
$nodes = $crawler->filter('ul li')->each(fn(Crawler $node) => $node->text());
$this->assertContains('test3', $nodes);
In Symfony 6.4, you can use the new assertions:
1 2
$this->assertAnySelectorTextSame('ul li', 'test 3');
$this->assertAnySelectorTextContains('ul li', 'test');
HttpClient Assertions
Symfony 6.4 also adds a few assertions to ensure that certain HTTP calls were triggered (via the HttpClient component) during the application execution:
1 2 3 4 5 6 7 8 9
// method arguments: (string) URL, (string) method, (string|array) body, (array) $headers, (string) http_client ID
$this->assertHttpClientRequest('https://example.com/', 'GET');
$this->assertHttpClientRequest('https://example.com/upload', 'POST', ['foo' => 'bar']);
// method arguments: (string) URL, (string) method, (string) http_client ID
$this->assertNotHttpClientRequest('https://example.com/other');
// method arguments: (int) count, (string) http_client ID
$this->assertHttpClientRequestCount(2);
Email Subject Assertions
Symfony already provides many assertions related to the mailer, such as
assertEmailCount()
, assertEmailTextBodyContains()
, assertEmailHasHeader()
, etc.
In Symfony 6.4 we're adding two new assertions related to the email subjects:
1 2
$this->assertEmailSubjectContains($email, 'Your order was processed successfully');
$this->assertEmailSubjectNotContains($email, 'Your order is pending');
Small typo in “already”:
Symfony alredy provides many assertions
Thanks Jeffrey! It's fixed now.