[英]Laravel testing with JWT-Auth
我正在嘗試測試由JWT_auth制成的api: https : //github.com/tymondesigns/jwt-auth
class UpdateTest extends TestCase
{
use DatabaseTransactions;
public $token;
public function signIn($data = ['email'=>'mail@gmail.com', 'password'=>'secret'])
{
$this->post('api/login', $data);
$content = json_decode($this->response->getContent());
$this->assertObjectHasAttribute('token', $content);
$this->token = $content->token;
return $this;
}
/** @test */
public function a_user_updates_his_account()
{
factory(User::class)->create([
'name' => 'Test',
'last_name' => 'Test',
'email' => 'mail@gmail.com',
'mobile' => '062348383',
'function' => 'ceo',
'about' => 'About me.....',
'corporation_id' => 1
]);
$user = User::first();
$user->active = 2;
$user->save();
$this->signIn();
$url = '/api/user/' . $user->slug . '?token=' . $this->token;
$result = $this->json('GET', $url);
dd($result);
}
}
結果總是:
The token could not be parsed from the request
我該如何工作!?
在這種情況下測試您的API的一種方法是繞過實際的令牌驗證,但仍要登錄您的用戶(如果您需要識別用戶)。 這是我們在最近的基於API的應用程序中使用的幫助程序方法的片段。
/**
* Simulate call api
*
* @param string $endpoint
* @param array $params
* @param string $asUser
*
* @return mixed
*/
protected function callApi($endpoint, $params = [], $asUser = 'user@example.org')
{
$endpoint = starts_with($endpoint, '/')
? $endpoint
: '/' . $endpoint;
$headers = [];
if (!is_null($asUser)) {
$token = auth()->guard('api')
->login(\Models\User::whereEmail($asUser)->first());
$headers['Authorization'] = 'Bearer ' . $token;
}
return $this->json(
'POST',
'http://api.dev/' . $endpoint,
$params,
$headers
);
}
和這樣使用:
$this->callApi('orders/list', [
'type' => 'customers'
])
->seeStatusOk()
基本上,目前還沒有真正的方法。 在測試期間創建並傳遞給Laravel進行處理的虛假請求,以某種方式刪除了令牌數據。
已經在一個問題中報告了該問題( https://github.com/tymondesigns/jwt-auth/issues/852 ),但是據我所知,目前還沒有解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.