Summer Sale! All accounts are 50% off this week.

Roni's avatar
Level 33

Post vs. Post Json

Hey this threw for for a crazy loop, so I thought I'd point it out here and maybe get some guidance.

I was writing up a test for my endpoint 'client.store', and in my validation I have a form request object that creates all the validation rules.

Now, in the app I was getting the right results and I know, very evil I was writing the test after the fact, I had changed implementations and hadn't upgraded the test yet.

I wrote what appeared to be the easiest test, and ... the test was failing, even the the app works correctly.

In the app I'm making an axios request to my client.store endpoint with a bunch of data and it throws all the correct errors but when I test it, I asserted the session had errors ... and it didn't.

Here is the test


    /** @test */
    public function a_client_under_care_requires_a_valid_care_facility() {
        $this->basicSignIn(User::first());
        $this->withExceptionHandling()
            ->postJson(route('client.store'),$this->getValidFields([
                'is_under_care' => 1
            ]))
            ->assertSessionHasErrors(['pcf.id', 'pcf.room']);


//which yields
Session is missing expected key [errors].
Failed asserting that false is true.

    }

I was ready to tear out my hair, and for no reason, I decided to change the postJson function to just post.


    /** @test */
    public function a_client_under_care_requires_a_valid_care_facility() {
        $this->basicSignIn(User::first());
        $this->withExceptionHandling()
            ->post(route('client.store'),$this->getValidFields([
                'is_under_care' => 1
            ]))
            ->assertSessionHasErrors(['pcf.id', 'pcf.room']);
    }


//works perfectly!?!?!

Since I am only ever invoking this route with an axios post request with a json payload, I just assumed that postJson was the most similar method. However it seems to bypass validation.

Any ideas? Does this seem odd?

Hope someone can shed some light on this or at least this might save someone an hour of checking every character for a non existent typo.

0 likes
4 replies
bobbybouwmann's avatar
Level 88

It depends on how you have implemented your routing. If your client.store route is in the web.php file then, yes this is correct that only post works. If your routes are in the api.php file, you have to use the json method otherwise you don't send the correct headers to make this work.

Does this make any sense to you?

Roni's avatar
Level 33

sorry @bobbybouwmann saw this the same day and it's a perfect answer, I forgot to mark it. Apologies.

mutisya's avatar

Laravel 8 has a helper to assert against validation errors when using postJson.

Use assertJsonValidationErrors(['your field'])

Please or to participate in this conversation.