Skip to content

Commit

Permalink
add assertions
Browse files Browse the repository at this point in the history
  • Loading branch information
freekmurze committed Dec 28, 2023
1 parent ce6f23b commit c3d0064
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/FakePdf.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,43 @@

namespace Spatie\LaravelPdf;

use Closure;
use Illuminate\Http\Response;
use PHPUnit\Framework\Assert;

class FakePdf extends Pdf
{
/** @var array<int, \Spatie\LaravelPdf\Pdf> */
protected array $respondedWithPdf = [];

public function assertViewIs(string $viewName): self
{
Assert::assertEquals($viewName, $this->viewName);

return $this;
}

public function toResponse($request): Response
{
$this->respondedWithPdf[] = $this;

return new Response();
}

public function assertRespondedWithPdf(Closure $expectations): void
{
Assert::assertNotEmpty($this->respondedWithPdf);

foreach($this->respondedWithPdf as $pdf) {

$result = $expectations($pdf);

if ($result === true) {
return;
}

}

Assert::fail('Did not respond with a PDF that matched the expectations');
}
}
18 changes: 18 additions & 0 deletions src/Pdf.php
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,24 @@ protected function hasHeader(string $headerName): bool
{
return array_key_exists($headerName, $this->responseHeaders);
}

public function isInline(): bool
{
if (! $this->hasHeader('Content-Disposition')) {
return false;
}

return str_contains($this->responseHeaders['Content-Disposition'], 'inline');
}

public function isDownload(): bool
{
if (! $this->hasHeader('Content-Disposition')) {
return false;
}

return str_contains($this->responseHeaders['Content-Disposition'], 'attachment');
}
}

/*
Expand Down
19 changes: 19 additions & 0 deletions tests/FakePdfTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<?php

use Illuminate\Support\Facades\Route;
use Spatie\LaravelPdf\Facades\Pdf;
use function \Spatie\LaravelPdf\Support\pdf;

it('can determine the view that was used', function () {
Pdf::fake();
Expand All @@ -9,3 +11,20 @@

Pdf::assertViewIs('test');
});

it('can determine the data that was passed to the view', function () {
Pdf::fake();

Route::get('pdf', function() {
return pdf('test')->inline();
});

$this
->get('pdf')
->assertSuccessful();

Pdf::assertRespondedWithPdf(function(\Spatie\LaravelPdf\Pdf $pdf) {
return $pdf->viewName === 'test'
&& $pdf->isInline();
});
});

0 comments on commit c3d0064

Please sign in to comment.