mardi 17 novembre 2020

How do you mock the Auth::id in Laravel 6 testing?

I'm trying to test a post route in a my laravel project.

In my controller one of the fields grabs the Auth::id to insert into the database:

return Order::create([
        'user_id' => Auth::id(),
        *rest of inserts*
    ]);

This is the test function currently:

public function testCreateOrder()
{
    $user = new User([
        'id' => 1,
        *rest of user info*
    ]);

    $this->be($user);
    
    $data = [
        *order data*
    ];

    $response = $this->post('/order', $data);

    $response->assertStatus(201);
}

Once I test I receive:

Expected status code 201 but received 500.

When I dd$($response) in the testCreateOrder(), in the errorInfo I'm getting:

"Column 'user_id' cannot be null"

I've been trying for the past few hours to figure out how to mock the Auth::id somehow by using $this->be($user) and $this->actingAs($user) and a handful of other solutions in hopes it carry's to the controller are can be used there.

It's my first time testing in Laravel and I'm a little stumped with this one so any help would be greatly appreciated :).

Also, the function works in actuality, it's just the testing side that's causing me a few problems.

Aucun commentaire:

Enregistrer un commentaire