Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

normykinz's avatar

Testing Inertia with Validation

I wonder if anyone can help me out here.

I have a login form built using Inertia and Vue (I know I could use Breeze) and I'm trying to test the validation (using Pest). The test keeps insisting that Invalid JSON was returned from the route. and I'm not sure why. It certainly returns JSON in the browser with a Content-Type: application/json header, after redirecting. The status assertion is passing so I know the test is following redirects as expected.

public function create(): RedirectResponse
{
    $validator = validator([
        'email' => 'required',
        'password' => 'required',
    ]);

    $validator->validate();

    return redirect('/login');
}

it('requires an email and password')
    ->followingRedirects()
    ->post('/login')
    ->assertStatus(200)
    ->assertJsonFragment(['email']);
0 likes
9 replies
lolsokje's avatar

Does postJson('/login') instead of post('/login') work?

normykinz's avatar

@Sinnbeck I'm just about to look at it, but as far s :I can tell, the Inertia middleware handles a 422 by adding the validation errors and redirecting itself. At least, that's what happens in the browser.

normykinz's avatar

@Sinnbeck

It's very sumple.

    public function index(): Response
    {
        return inertia('Auth/Login');
    }
Sinnbeck's avatar

My best suggestion is to rewrite to a functional test instead of higher order, which should let you dd the response

Or add dd() to the chain and see if you get anything useful

normykinz's avatar

@Sinnbeck

I think you're right. Excellent as Inertia is, it's proving to be a bit of a pig to test.

I might just take a look at the tests in Breeze and see how they've handled things there though.

Thanks @sinnbeck

normykinz's avatar
normykinz
OP
Best Answer
Level 4

If anybody's having the similar problems, here's how managed to iron things out ...

public function create(LoginRequest $request): RedirectResponse
{
    return redirect('/login');
}
class LoginRequest extends FormRequest
{
    protected $redirect = "/login";

    public function rules()
    {
        return [
            'email' => 'required',
            'password' => 'required',
        ];
    }
}
it('requires an email and password')
    ->followingRedirects()
    ->post('/login')
    ->assertInertia(fn (Assert $page) => $page
        ->component('auth/Login')
        ->has('errors.email')
        ->has('errors.password'));
4 likes

Please or to participate in this conversation.