This commit is contained in:
fthvgb1 2018-06-16 10:54:07 +08:00
parent 1a81f8baee
commit 9f23419049
2 changed files with 131 additions and 0 deletions

View File

@ -0,0 +1,115 @@
<?php
namespace Tests\Feature;
use App\Models\Topic;
use App\Models\User;
use Tests\TestCase;
use Tests\Traits\ActingJWTUser;
class TopicApiTest extends TestCase
{
use ActingJWTUser;
protected $user;
public function setUp()
{
parent::setUp();
$this->user = factory(User::class)->create();
}
public function testStoreTopic()
{
$data = ['category_id' => 1, 'body' => 'test body', 'title' => 'test title'];
$token = \Auth::guard('api')->fromUser($this->user);
$request = $this->withHeaders(['Authorization' => 'Bearer ' . $token])
->json('POST', '/api/topics', $data);
$assertData = [
'category_id' => 1,
'user_id' => $this->user->id,
'title' => 'test title',
'body' => clean('test body', 'user_topic_body'),
];
$request->assertStatus(201)
->assertJsonFragment($assertData);
}
/**
* A basic test example.
*
* @return void
*/
public function testExample()
{
$this->assertTrue(true);
}
public function testUpdateTopic()
{
$topic = $this->makeTopic();
$editData = ['category_id' => 2, 'body' => 'edit body', 'title' => 'edit title'];
$response = $this->JWTActingAs($this->user)
->json('PATCH', '/api/topics/' . $topic->id, $editData);
$assertData = [
'category_id' => 2,
'user_id' => $this->user->id,
'title' => 'edit title',
'body' => clean('edit body', 'user_topic_body'),
];
$response->assertStatus(200)
->assertJsonFragment($assertData);
}
protected function makeTopic()
{
return factory(Topic::class)->create([
'user_id' => $this->user->id,
'category_id' => 1,
]);
}
public function testShowTopic()
{
$topic = $this->makeTopic();
$response = $this->json('GET', '/api/topics/' . $topic->id);
$assertData = [
'category_id' => $topic->category_id,
'user_id' => $topic->user_id,
'title' => $topic->title,
'body' => $topic->body,
];
$response->assertStatus(200)
->assertJsonFragment($assertData);
}
public function testIndexTopic()
{
$response = $this->json('GET', '/api/topics');
$response->assertStatus(200)
->assertJsonStructure(['data', 'meta']);
}
public function testDeleteTopic()
{
$topic = $this->makeTopic();
$response = $this->JWTActingAs($this->user)
->json('DELETE', '/api/topics/' . $topic->id);
$response->assertStatus(204);
$response = $this->json('GET', '/api/topics/' . $topic->id);
$response->assertStatus(404);
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace Tests\Traits;
use App\Models\User;
trait ActingJWTUser
{
public function JWTActingAs(User $user)
{
$token = \Auth::guard('api')->fromUser($user);
$this->withHeaders(['Authorization' => 'Bearer ' . $token]);
return $this;
}
}