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

Marijn's avatar

Vscode gives error when trying to do the 'actingAs()' method in my feature tests

Simple question: how can I type hint to vscode that the User::factory()->create() method returns an authenticatable, an interface that $this->actingAs(...) in the feature tests expects?

0 likes
5 replies
bobbybouwmann's avatar
Level 88

The return type of create on the factory in this case is always Model. This is the parent class of all models. So instead you need to tell your editor that you get a specific model back

/** @var User $user */
$user = User::factory()->create();

The User model implements the Authenticatable interface, so this should work

2 likes
Marijn's avatar

@bobbybouwmann Any way to do this in order to still be able to remove the variable? so like this response = $this->actingAs(User::factory()->create())->post...

bobbybouwmann's avatar

@Marijn Well, your above is valid PHP code. It's just that your editor doesn't understand it. So you can keep it like this, and live with the message ;)

Amirho3ein's avatar

Hi , you have to login after u create the user

$user= User::factory()->create();

    $response = $this->post('/login', [
        'email' => $user->email,
        'password' => 'password',
    ]);
MizouziE's avatar

Thanks to the answers here, I managed to find a work around that doesn't damage the tests and tweaks the type returned by create() so that vscode is satisfied.

If you add these two extra parts, it will stop squawking when you use the created $user inside the actingAs() method.

...
use Illuminate\Contracts\Auth\Authenticatable; // <- this part is added

class SomeTest extends TestCase
{
    use RefreshDatabase, WithFaker;

    /**
     * Test for user seeing some list.
     */
    public function test_a_user_can_see_a_thing(): void
    {
        /** @var Authenticatable $user */ // <- and this part
        $user = User::factory()->create();

        $thing =Thing::factory()->create();

        $response = $this->actingAs($user)->getJson(route('thing.show', ['id' => $thing->id]));
        $response
            ->assertJson(
                fn (AssertableJson $json) =>
                $json->where('thing.id', $thing->id)
                    ->etc()
            );
    }

Please or to participate in this conversation.