Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code coverage for laravel dusk

Is there any way to get code coverage when running Laravel Dusk?

I know it runs browser tests so it's not scrutinizing code, but is there a way to add a listener to check what code is covered? I did not see anything on this subject now.

like image 607
rap-2-h Avatar asked Apr 27 '17 09:04

rap-2-h


2 Answers

Conceptually, you need to bootstrap all your requests w/ PHP Unit's code coverage tools.

You can do this with phpunit libraries directly, or via xdebug's coverage tools (which use phpunit).

From this sample gist that I found, you can start coverage tools based on a couple of _GET parameters passed via the Dusk test.

public function testBasicExample()
{
      $this->browse(function (Browser $browser) {
          $browser->visit(route('test', [
              'test_name' => 'testBasicExample',
              'coverage_dir' => '/app/Http'
          ]))->assertSee('test');
      });
  }

The code that does the work is two parts 1. Start collecting based on parameters:

$test_name = $_GET['test_name'];
require __DIR__ . '/../vendor/autoload.php';
$current_dir = __DIR__;
$coverage = new SebastianBergmann\CodeCoverage\CodeCoverage;
$filter = $coverage->filter();
$filter->addDirectoryToWhitelist(
    $current_dir . '/..' . ((isset($_GET['coverage_dir']) && $_GET['coverage_dir'])
        ? $_GET['coverage_dir']
        : '/app')
);
$coverage->start($test_name);

And 2 end collecting and output:

function end_coverage()
{
    global $test_name;
    global $coverage;
    global $filter;
    global $current_dir;
    $coverageName = $current_dir . '/coverages/coverage-' . $test_name . '-' . microtime(true);
    try {
        $coverage->stop();
        $writer = new \SebastianBergmann\CodeCoverage\Report\Html\Facade;
        $writer->process($coverage, $current_dir . '/../public/report/' . $test_name);
        $writer = new SebastianBergmann\CodeCoverage\Report\PHP();
    } catch (Exception $ex) {
        file_put_contents($coverageName . '.ex', $ex);
    }
}

The end collection is called using a clever little trick where the class coverage_dumper has just a destructor, which gets called automatically when php ends the process.

The code itself can use a bit of tidy up as far as output paths, and variables go, but from a concept, it should work.

like image 72
Darryl E. Clarke Avatar answered Sep 21 '22 12:09

Darryl E. Clarke


Dusk is using Browsers to run tests and the Browser can't see the PHP code that's being executed. The only way that I see to achieve code coverage with Dusk is to create a option in php artisan serve that would be possible to count and create the coverage file.

like image 35
Deric Lima Avatar answered Sep 18 '22 12:09

Deric Lima