I just added tymondesigns/jwt-auth to support token auth, and consequently my test cases are failing because there is no token on the headers parameters. How can I mock (using Mockery
) a component to bypass this?
Note: $this->be()
doesn't work
An alternative is to authenticate the request during test execution passing a particular user. This is how did it:
# tests/TestCase.php
/**
* Return request headers needed to interact with the API.
*
* @return Array array of headers.
*/
protected function headers($user = null)
{
$headers = ['Accept' => 'application/json'];
if (!is_null($user)) {
$token = JWTAuth::fromUser($user);
JWTAuth::setToken($token);
$headers['Authorization'] = 'Bearer '.$token;
}
return $headers;
}
Then in my tests I use it like this:
# tests/StuffTest.php
/**
* Test: GET /api/stuff.
*/
public function testIndex()
{
$url = '/api/stuff';
// Test unauthenticated access.
$this->get($url, $this->headers())
->assertResponseStatus(400);
// Test authenticated access.
$this->get($url, $this->headers(User::first()))
->seeJson()
->assertResponseOk();
}
Hope this help you all. Happy coding!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With