jeudi 12 novembre 2020

Laravel 8 PHPUnit -Invalid JSON was returned from the route

Alright so I'm pretty new to both unit testing, Fakers and laravel. I'm trying to unit test my resource controller, but I'm stuck at the update function.

Here's my controller:

public function update(Request $request, $id)
    {
        DB::beginTransaction();
        try {
            $oOrder = Order::with(['contact', 'contact.company'])->find($id);
            $bChangeStatus = $oOrder->status !== $request->status;
            $oOrder->fill($request->all());
            $oOrder->save();

            // update the status
            if ($bChangeStatus && $request->status === 'canceled') {
                Transport_order::where('order_id', $id)
                    ->whereNotIn('status', ['billed', 'delivered'])
                    ->update(['status' => 'canceled']);
            }
            // ....... the same if conditions for other status
            
            $oOrder->equipments()->sync($request->equipment_ids);
            DB::commit();
            return $oOrder;
        } catch (\Exception $e) {
            DB::rollback();
            abort(400, $e);
        }
    }

Here is my update test

    function test_can_update_an_order()
{
    $order = Order::factory()->create(['status' => 'draft']); // other attributes from the factory definition

    $this->putJson("api/orders/{$order->id}", ['status' => 'cancelled'])
        ->assertStatus(200)
        ->assertJsonFragment(['status' => 'cancelled']);

    // Make assertions about other side-effects for **this** particular action.
}

When I run this code I get the error :

Expected status code 200 but received 405. Failed asserting that 200 is identical to 405

Any help is welcome ! Thank you very much !

Aucun commentaire:

Enregistrer un commentaire