Best way to write unit tests ? #1371
-
What do you guys think is the best way of writing testcases using Inertia ? I currently use something like this for my front-end pages. This current Feature Test will check if
You can ignore the <?php
namespace Tests\Feature;
use App\Models\Article;
use Inertia\Testing\AssertableInertia as Assert;
class PublicPagesTest extends BaseTestCase
{
public function test_home_page_can_be_rendered_and_has_correct_props(): void
{
$this->get(route('pages.home'))
->assertInertia(fn (Assert $page) => $page
->component('Home/Index')
->has('content')
);
}
public function test_articles_page_can_be_rendered_and_has_correct_props(): void
{
$this->get(route('pages.article'))
->assertInertia(fn (Assert $page) => $page
->component('Articles/Index')
->has('articles', fn (Assert $page) => $page
->has('name')
// etc
)
);
}
public function test_single_article_page_can_be_rendered_and_has_correct_props(): void
{
$randomArticle = Article::all()->random();
$this->get(route('pages.article', $randomArticle->slug))
->assertInertia(fn (Assert $page) => $page
->component('Articles/Show')
->has('article.data', fn (Assert $page) => $page
->has('article.data')
->where('name', $randomArticle->name)
->where('content', $randomArticle->content)
// etc
)
);
}
}
// More tests My PageController looks something like this <?php
namespace App\Http\Controllers;
use App\Http\Resources\Content\ContentResource;
use App\Http\Resources\Article\ArticleCollection;
use App\Http\Resources\Article\ArticleResource;
use App\Models\Article;
use Illuminate\Support\Facades\Lang;
use Inertia\Inertia;
use Inertia\Response;
class PageController extends Controller
{
/**
* Home Page
*
* @return Response
*/
public function index(): Response
{
$content = Lang::get('pages/home');
return Inertia::render('Home/Index', [
'content' => new ContentResource($content),
]);
}
/**
* Articles
*
* @param [type] $slug
* @return void
*/
public function articlePage($slug = null)
{
if ($slug) {
$article = Article::published()
->where('slug', $slug)
->first();
if (!$article) {
abort(404);
}
return Inertia::render('Article/Show', [
'article' => new ArticleResource($article),
]);
}
$articles = Article::published()
->orderBy('start_time', 'DESC')
->get();
return Inertia::render('Article/Index', [
'articles' => new ArticleCollection($articles),
]);
}
} Is there a better way to make tests like this, or is this the prefered way ? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Basically this is the way of the make the tests with InertiaJs. I do it the some way. |
Beta Was this translation helpful? Give feedback.
Basically this is the way of the make the tests with InertiaJs. I do it the some way.