我正在尝试测试用JWT_auth:https://github.com/tymondesigns/jwt-auth制作的api
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我怎么才能做到这一点!?
发布于 2016-10-20 21:51:05
在这种情况下测试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()发布于 2016-10-20 17:53:37
基本上,目前还没有真正的解决办法。在测试过程中创建并传递给Laravel处理的虚假请求以某种方式删除了令牌数据。
它已经被报道在一个问题(https://github.com/tymondesigns/jwt-auth/issues/852),但据我所知,还没有解决办法。
https://stackoverflow.com/questions/40151658
复制相似问题