3

I am running test in laravel . But it is failing test. I am not getting the reason may because of middleware but not sure.

Here is test function

public function test_example()
    {
        $staff = factory(Staff::class)->create();
        $response = $this->actingAs($staff) 
        ->withSession(['foo' => 'bar'])
            ->get('/products');

        $response->assertStatus(200);
    }
}

Here is the output

   PHPUnit\TextUI\Command::main()


  Tests:  1 failed, 2 passed
  Time:   0.98s

PS C:\projects\coldxlogistics> php artisan test
Warning: TTY mode is not supported on Windows platform.

   PASS  Tests\Feature\DashboardTest
  ✓ dashboard loads fine
  ✓ user cannot see dashboard without login

   FAIL  Tests\Feature\ProductTest
  ⨯ example

  ---

  • Tests\Feature\ProductTest > example
  Expected status code 200 but received 302.
  Failed asserting that 200 is identical to 302.

  at C:\projects\coldxlogistics\tests\Feature\ProductTest.php:24
     20▕         $response = $this->actingAs($staff)
     21▕         ->withSession(['foo' => 'bar'])
     22▕             ->get('/products');
     23▕
  ➜  24▕         $response->assertStatus(200);
     25▕     }
     26▕ }
     27▕

  1   C:\projects\coldxlogistics\vendor\phpunit\phpunit\phpunit:61
      PHPUnit\TextUI\Command::main()


  Tests:  1 failed, 2 passed
  Time:   1.00s

There are multiple middlwares working on routes. for Example

auth,login_auth,two_factor_auth

and what is the purpose of withSession() how to use it? i see the documentation but can;t understand what is foo, bar

  • `withSession()` is pretty clearly explained in the [docs](https://laravel.com/docs/8.x/http-tests#session-and-authentication) in my opinion, what exactly do you not understand? It stores the given values in the session: "_You may set the session data to a given array using the `withSession` method. This is useful for loading the session with data before issuing a request to your application._" – Remul Jan 18 '21 at 09:49
  • And a 302 response means that your request was redirected, but without seeing all the code that the request has to pass through no one will be able to help you, seems strange to me though that you have 3 auth middlewares on your route: `auth,login_auth,two_factor_auth`, maybe check if one of those is redirecting your request. – Remul Jan 18 '21 at 10:00
  • It means that if i need to visit route on which middleware is implemented. then I should send stored value of session? currently i am not getting why it is redirecting back. I think because user is not authenticated. –  Jan 18 '21 at 10:11
  • The 302 is redirection & you need to handle non-auth requests as well, use assertRedirect($uri), would assert whether the response is redirecting to a given URI – bhucho Jan 18 '21 at 11:40

0 Answers0