Skip to content

Commit

Permalink
Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ycs77 committed May 28, 2024
1 parent 5856a7d commit 1e04cbf
Show file tree
Hide file tree
Showing 9 changed files with 291 additions and 4 deletions.
15 changes: 13 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,26 @@
"symfony/console": "^7.0"
},
"require-dev": {
"laravel/pint": "^1.13"
"laravel/pint": "^1.13",
"orchestra/testbench": ">=9.0",
"pestphp/pest": "^2.34",
"pestphp/pest-plugin-laravel": "^2.4"
},
"autoload": {
"psr-4": {
"Inertia\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Inertia\\Engage\\Tests\\": "tests"
}
},
"config": {
"sort-packages": true
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true
}
},
"extra": {
"laravel": {
Expand Down
18 changes: 18 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.3/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory suffix=".php">./app</directory>
<directory suffix=".php">./src</directory>
</include>
</source>
</phpunit>
2 changes: 0 additions & 2 deletions src/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,6 @@ public function errorMessageKey(string $key)
protected function messages(): array
{
return [
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
419 => 'The page expired, please try again.',
Expand Down
186 changes: 186 additions & 0 deletions tests/Feature/Exceptions/ExceptionHandlerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
<?php

use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response as LaravelResponse;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\ValidationException;
use Inertia\Exceptions\Handler;
use Inertia\ResponseFactory;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

dataset('methods', [
['GET'],
['POST'],
['PUT'],
['PATCH'],
['DELETE'],
]);

dataset('response_type', [
'general html (enabled debug)' => [$debug = true, $inertia = false],
'inertia html (disabled debug)' => [$debug = false, $inertia = false],
'inertia json (disabled debug)' => [$debug = false, $inertia = true],
]);

describe('http error response', function () {
dataset('exceptions', [
[403, 'Forbidden', fn () => new AccessDeniedHttpException('This action is unauthorized.')],
[404, 'Not Found', fn () => new NotFoundHttpException('The route / could not be found.')],
[500, 'Server Error', fn () => new ErrorException('Undefined variable $fail')],
[503, 'Service Unavailable', fn () => new HttpException(503, 'Service Unavailable')],
]);

test('general html (enabled debug)', function (int $code, string $message, Exception $exception, string $method) {
Config::set('app.debug', true);

$handler = new Handler(app(ResponseFactory::class));

$request = Request::create('http://localhost/', $method);

$response = new LaravelResponse(
content: "<!DOCTYPE html><html><head><title>{$message}</title></head><body><h1>{$code} {$message}</h1></body></html>",
status: $code
);

$response = $handler->handle($request, $response, $exception);

expect($response->getStatusCode())->toBe($code);
expect($response->getContent())->toContain('<!DOCTYPE html>');
expect($response->getContent())->not->toContain('@inertia');
})->with('exceptions')->with('methods');

test('inertia html (disabled debug)', function (int $code, string $message, Exception $exception, string $method) {
Config::set('app.debug', false);

$handler = new Handler(app(ResponseFactory::class));

$request = Request::create('http://localhost/', $method);

$response = new LaravelResponse(
content: "<!DOCTYPE html><html><head><title>{$message}</title></head><body><h1>{$code} {$message}</h1></body></html>",
status: $code
);

$response = $handler->handle($request, $response, $exception);

expect($response->getStatusCode())->toBe($code);
expect($response->getContent())->toContain('<!DOCTYPE html>');
expect($response->getContent())->toContain('@inertia');
})->with('exceptions')->with('methods');

test('inertia json (disabled debug)', function (int $code, string $message, Exception $exception, string $method) {
Config::set('app.debug', false);

$handler = new Handler(app(ResponseFactory::class));

$request = Request::create('http://localhost/', $method);
$request->headers->set('X-Inertia', 'true');

$response = new LaravelResponse(
content: "<!DOCTYPE html><html><head><title>{$message}</title></head><body><h1>{$code} {$message}</h1></body></html>",
status: $code
);

$response = $handler->handle($request, $response, $exception);

expect($response->getStatusCode())->toBe($code);
expect($response->getContent())->toBeJson('{"component":"Error","props":{"code":'.$code.',"message":"'.$message.'"},"url":"\/","version":""}');
})->with('exceptions')->with('methods');
});

test('419 page expired', function (bool $debug, bool $inertia) {
Config::set('app.debug', $debug);
Session::setPreviousUrl('http://localhost/form');

$handler = new Handler(app(ResponseFactory::class));

$request = Request::create('http://localhost/save', 'POST');
if ($inertia) {
$request->headers->set('X-Inertia', 'true');
}

$exception = new TokenMismatchException('CSRF token mismatch.');
$exception = new HttpException(419, $exception->getMessage(), $exception);

$response = new LaravelResponse(
content: '<!DOCTYPE html><html><head><title>Page Expired</title></head><body><h1>419 Page Expired</h1></body></html>',
status: 419
);

/** @var Illuminate\Http\RedirectResponse */
$response = $handler->handle($request, $response, $exception);

expect($response)->toBeInstanceOf(RedirectResponse::class);
expect($response->getStatusCode())->toBe(302);
expect($response->getContent())->toContain('Redirecting to http://localhost/form');

$session = $response->getSession();
expect($session->get('error'))->toBe('The page expired, please try again.');
})->with('response_type');

test('422 validation failed', function (bool $debug, bool $inertia) {
Config::set('app.debug', $debug);
Session::setPreviousUrl('http://localhost/form');

$handler = new Handler(app(ResponseFactory::class));

$request = Request::create('http://localhost/save', 'POST');
if ($inertia) {
$request->headers->set('X-Inertia', 'true');
}

$exception = ValidationException::withMessages([
'name' => 'The name field is required.',
]);

$response = new RedirectResponse('http://localhost/form');
$response->setSession(app('session.store'));
$response->withErrors($exception->errors(), $exception->errorBag);

/** @var Illuminate\Http\RedirectResponse */
$response = $handler->handle($request, $response, $exception);

expect($response)->toBeInstanceOf(RedirectResponse::class);
expect($response->getStatusCode())->toBe(302);
expect($response->getContent())->toContain('Redirecting to http://localhost/form');

$session = $response->getSession();
expect($session->get('errors')->toArray())->toBe([
'name' => ['The name field is required.'],
]);
})->with('response_type');

test('429 too many requests', function (bool $debug, bool $inertia) {
Config::set('app.debug', $debug);
Session::setPreviousUrl('http://localhost/form');

$handler = new Handler(app(ResponseFactory::class));

$request = Request::create('http://localhost/save', 'POST');
if ($inertia) {
$request->headers->set('X-Inertia', 'true');
}

$exception = new ThrottleRequestsException('Too Many Attempts.');

$response = new LaravelResponse(
content: '<!DOCTYPE html><html><head><title>Too Many Requests</title></head><body><h1>429 Too Many Requests</h1></body></html>',
status: 429
);

/** @var Illuminate\Http\RedirectResponse */
$response = $handler->handle($request, $response, $exception);

expect($response)->toBeInstanceOf(RedirectResponse::class);
expect($response->getStatusCode())->toBe(302);
expect($response->getContent())->toContain('Redirecting to http://localhost/form');

$session = $response->getSession();
expect($session->get('error'))->toBe('Too Many Requests');
})->with('response_type');
17 changes: 17 additions & 0 deletions tests/Feature/Pagination/PaginatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

use Inertia\Pagination\Paginator;

test('should return the URL for a given page number', function () {
$paginator = new Paginator(
items: collect(range(1, 100)),
total: 100,
perPage: 10,
currentPage: 1,
options: ['path' => 'http://example.com']
);

expect($paginator->url(page: 1))->toBe('http://example.com');
expect($paginator->url(page: 2))->toBe('http://example.com?page=2');
expect($paginator->url(page: 3))->toBe('http://example.com?page=3');
});
15 changes: 15 additions & 0 deletions tests/Feature/ServiceProviderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

test('should get the overrided paginator class', function () {
$paginator = app()->make(\Illuminate\Pagination\LengthAwarePaginator::class, [
'items' => [],
'total' => 0,
'perPage' => 10,
]);

expect($paginator)->toBeInstanceOf(\Inertia\Pagination\Paginator::class);
});

test('should called exception handler from inertia response factory', function () {
expect(\Inertia\ResponseFactory::hasMacro('exception'))->toBeTrue();
});
5 changes: 5 additions & 0 deletions tests/Pest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

use Inertia\Engage\Tests\TestCase;

uses(TestCase::class)->in('Feature');
24 changes: 24 additions & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace Inertia\Engage\Tests;

use Inertia\EngageServiceProvider;
use Orchestra\Testbench\Concerns\WithWorkbench;
use Orchestra\Testbench\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
// use WithWorkbench;

protected function defineEnvironment($app)
{
$app['view']->addLocation(__DIR__.'/stubs/views');
}

protected function getPackageProviders($app)
{
return [
EngageServiceProvider::class,
];
}
}
13 changes: 13 additions & 0 deletions tests/stubs/views/app.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">

@inertiaHead
</head>

<body>
@inertia
</body>
</html>

0 comments on commit 1e04cbf

Please sign in to comment.