0

I'm a noob in unit testing and I want to test my API. So, LexikJWTAuthenticationBundle works fine when I try to access in /login_check path and the CRUL command line. But when I try to do the TestCase I get this error :

1) Tests\AppBundle\Controller\StoreControllerTest::testPOSTRate GuzzleHttp\Exception\ClientException: Client error: GET http://localhost:8000/api/stores resulted in a 401 Unauthorized response: {"code":401,"message":"Invalid JWT Token"}

My testPOST function :

public function testPOSTRate(){
    $data = array(
      'rate' => 1,
      'store' => 1
    );
    // I'm not sure if it's the right way to get Token
    $token = $this->getService('lexik_jwt_authentication.encoder')->encode([
      'username' => 'Nacer',
      ]);

    $this->client->get('http://localhost:8000/api/stores', [
      'body' => json_encode($data),
      'headers' => [
        'Authorization' => 'Bearer '.$token
      ]
    ]);
  }

1 Answers1

1

Try creating the token this way

$token = $this->get('lexik_jwt_authentication.jwt_manager')->create($userFull);

where $userfull is an instance of UserInterface( an user object).

In order to be sure the token is valid you can always do a dump($token);die; and see. Let me know if solved your problem.

Notice I am calling the service from the controller, that's why the $this->get. Otherwhise you need to inject the service or the service container in order to get access to all of the services.

If that did not work add this

 'headers' => [
    'Authorization: Bearer '.$token
  ]