0

Image 1

When I check dd(\Auth()::check()); in testLoginTrue method in LoginTest case then it's returning true but when I use dd(\Auth()::check()); in testClientCreateFormDisplayed method in ClientTest then it's returning false.

Image 2

So how can I get a logged in user in another test case? Is that need to login user before every test case?

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
Hardik Patel
  • 11
  • 1
  • 2
  • 1
    what is your login system? do you have user sessions? do your login tokens expire after a short time? We need way more information on this if we are to help you. – Mash tan Jun 09 '22 at 08:14
  • It's normal laravel login system. public function testLoginTrue() { $credential = [ 'email' => 'example@gmail.com', 'password' => 'test@123' ]; $this->post('login',$credential)->assertRedirect('dashboard'); dump(\Auth()::user()); // it's return user data dd(\Auth()::check()); // it's return false } public function testLoginFalse() { dump(\Auth()::user()); // it's return null dd(\Auth()::check()); // it's return false } – Hardik Patel Jun 09 '22 at 08:30
  • Do not share images as they will eventually go down rendering this questions useless, remember to always share text code. And one more thing, you are testing the login functionality... you are using the Laravel's login (it is not your own implementation) so you are testing the framework... of course doing the right login with the correct user and pass will work, so you don't have to test that... – matiaslauriti Jun 09 '22 at 13:31

1 Answers1

3

It's in their docs https://laravel.com/docs/9.x/http-tests#session-and-authentication,

So just add in ->actingAs($user) just before a get/post

If you need the user after creating it (or just in general) - you can always just grab it from the database in the test

Ben Gooding
  • 884
  • 9
  • 18
  • public function testLoginTrue() { $credential = [ 'email' => 'example@gmail.com', 'password' => 'test@123' ]; $this->post('login',$credential)->assertRedirect('dashboard'); dump(\Auth()::user()); // it's return user data dd(\Auth()::check()); // it's return false } public function testLoginFalse() { dump(\Auth()::user()); // it's return null dd(\Auth()::check()); // it's return false } – Hardik Patel Jun 09 '22 at 09:04
  • I dont want to create user in **testLoginFalse** function, because user already in database and it's logged in by **testLoginTrue** function. – Hardik Patel Jun 09 '22 at 09:04
  • @HardikPatel no, if you already have the user, you don't need to create it again unless you are using a property of that user that needs to be different from the existing one. So you just need to do `->actingAs(...)` again, because when you run a new test, everything else is reset after the test finishes and a new one starts, so you are not logged in again... Read the documentation Ben shared on his answer please... – matiaslauriti Jun 09 '22 at 13:31