
いつ使うの?
- SPAではないプロジェクト(アクセストークンの取得タイミングがMPAでのログイン時)
- 一部画面でアクセストークンを含むAPIを叩いている
コード
<?php
use Tests\TestCase;
class SampleControllerTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
$res = $this->post('/login', [
'email' => 'hoge@example.jp',
'password' => 'password'
]);
$this->accessToken = $res->baseResponse->getSession()->get('access_token');
}
public function testAPIリクエスト()
{
$res = $this->post('api/hoge', ['product_id' => 1], ['Authorization' => 'Bearer ' . $this->accessToken]);
$res->assertOk()->assertJson(['succeeded' => true]);
}
}
要点
setUp()
時にアクセストークンの発行処理を実施し、プロパティにアクセストークンを入れておく
- テストの時にプロパティに入っているアクセストークンを含めてリクエストの発行をする
- アクセストークン取得時のリクエストはAPIのエンドポイントではないのでアクセストークン自体は
\Illuminate\Http\Response
が入っている baseResponse
から取得する
- API経由で取得する場合は
$res->json($key)
で取得できるっぽい(未検証)
(※decodeResponseJson()
の引数にkeyを指定して取得できてたみたいだけどLaravel8からは引数を取らないみたい)
github.com
readouble.com
qiita.com
