Wednesday, September 13, 2023
HomePHPSymfony'' s DomCrawler with Laravel HTTP Evaluates|Laravel Information

Symfony'' s DomCrawler with Laravel HTTP Evaluates|Laravel Information


Have you ever before required to insist component of an HTML feedback from within an HTTP examination in Laravel? I just recently required to verify components of a reaction to confirm an essential item of material was made. As an example, allow’s state you have an essential JavaScript data that you wish to guarantee is had within the DOM?

Right here’s the screening API we are mosting likely to develop:

$ node = $feedback->> obtain('/')

->> crawl()

->> filter(' a')

->> decrease( feature ( Spider $node): bool {

return $node->> attr(' href') == = ' https://laravel-news.com';

} );

$ this->> assertCount( 1, $node);

There are a couple of choices for parsing and also going across the DOM within PHP, such as PHP’s DOMDocument, PHPUnit’s DOM assertions (which are deprecated), Symfony’s DOMCrawler part, and also different others. I take place to like Symfony’s DOMCrawler part, which has actually effective filtering system, traversal and also even more.

Allow’s see exactly how we can swiftly integrate the DOMCrawler part in our Laravel HTTP examinations!

Instance

The idea of utilizing the DOMCrawler is producing a brand-new Spider circumstances with the HTML material passed to the contractor:

usage SymfonyComponentDomCrawlerCrawler;

$ crawler = brand-new Spider($ feedback->> getContent());

foreach ($ crawler as $domElement) {

var_dump($ domElement->> nodeName);

}

Utilizing the Spider circumstances straight functions however is repeated. Offered Laravel’s effective macro attribute, we can swiftly specify a macro to creep a TestResponse

Right Here’s what the use of my macro resembles:

$ feedback = $ this->> obtain('/');

$ crawler = $feedback->> crawl();

// DOM traversal

// Assertions

If you wish to attempt it out, specify the complying with macro in a company’s boot() technique:

usage IlluminateSupportServiceProvider;

usage IlluminateTestingTestResponse;

usage SymfonyComponentDomCrawlerCrawler;

usage PHPUnitFrameworkAssert as PHPUnit;

// ...

public feature boot(): gap

{

TestResponse:: macro(' crawl', feature(? callable $callback = void): Spider {

if ( vacant($ material = $ this->> getContent())) {

PHPUnit:: stop working(' The HTTP feedback is vacant.');

}

$callback ?? = fn ($ c): Spider => > $c;

return call_user_func($ callback, brand-new Spider($ material));

} );

}

Our macro does the following:

  1. Obtain the feedback material and also stop working the examination promptly if it’s vacant
  2. Produce a pass-through callback if the individual really did not give one utilizing the void integrating task driver
  3. Pass a brand-new Spider circumstances via the callback, which need to return a Spider circumstances in the long run

Utilizing the void integrating task driver, we stay clear of any kind of if checks by giving a default pass-through callback if the individual does not pass one.

The concept of the callable is that the individual might go across the DOM, do some assertions, and also eventually return a part of the DOM through crawl() so a component of the DOM is required:

// Return the complete material

$ crawler = $feedback->> crawl();

// Filter and also return the filteringed system spider circumstances

$ card = $feedback->> crawl( feature ( Spider $c) {

return $c->> filter(' a')

->> decrease( feature ( Spider $node) {

return $node->> attr(' href') == = ' https://laravel-news.com';

} );

} );

Possibly this instance is a little bit excessive, however allow’s verify the Laravel Information HTML consisted of in the welcome.blade.php within a default Laravel installment:

usage SymfonyComponentDomCrawlerCrawler;

// ...

/ **

* A standard examination instance.

*/

public feature test_the_application_returns_a_successful_response(): gap

{

$feedback = $ this->> obtain('/');

$feedback->> assertStatus( 200);

// Locate the Laravel Information node

$card = $feedback->> crawl()

->> filter(' a')

->> decrease( feature ( Spider $node) {

return $node->> attr(' href') == = ' https://laravel-news.com';

} );

$ this->> assertNotEmpty($ card, ' The Laravel Information homepage card was not discovered!');

// Verify that the $card node has an H2 with 'Laravel Information'

$ this->> assertEquals(

' Laravel Information',

$card->> filter(' h2')->> initially()->> message()

);

// Verify that the web page reveals the blurb

$blurb = $card

->> filter(' p')

->> decrease( feature ( Spider $n) {

return str($ n->> message())->> startsWith(' Laravel Information is a neighborhood driven website');

} );

$ this->> assertCount( 1, $blurb);

}

Benefit

You might wish to compose even more ease assistants to verify DOM components in your examinations. As an example, below’s an easy assertion that verifies a node exists:

$ feedback

->> assertStatus( 200)

->> assertNodeExists(' a[href="https://laravel-news.com"]');

As Well As below’s the macro I have actually specified, which additionally enables chaining with the TestResponse circumstances:

TestResponse:: macro(' assertNodeExists', feature( string $selector): fixed {

$node = $ this->> crawl()->> filter($ selector);

$message = " Fell short insisting the node exists with selector " {$ selector} "";

PHPUnit:: assertGreaterThan( 0, $node->> matter(), $message);

return $ this;

} );

If the node does not exist, below’s an instance of what our macro will certainly appear like in our examination result:

1) TestsFeatureExampleTest:: test_the_application_returns_a_successful_response

Fell short insisting the node exists with selector "a[href="https://laravelnews.com"]".

Fell short insisting that 0 is more than 0.

I would certainly suggest having a look at the capacities of the Harmony The DomCrawler Part It consists of effective XPath and also CSS selectors, node traversal, and also much more!

RELATED ARTICLES

Most Popular

Recent Comments