aiblog/tests/Feature/PostViewTest.php
2024-11-17 11:30:01 +08:00

59 lines
No EOL
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class PostViewTest extends TestCase
{
use RefreshDatabase;
public function test_post_view_count_increases(): void
{
$post = Post::factory()->create();
$user = User::factory()->create();
$this->actingAs($user)
->getJson("/api/posts/{$post->id}");
$this->assertEquals(1, $post->fresh()->views);
}
public function test_same_ip_does_not_increase_view_count_within_24_hours(): void
{
$post = Post::factory()->create();
$user = User::factory()->create();
$this->actingAs($user)
->getJson("/api/posts/{$post->id}");
$this->actingAs($user)
->getJson("/api/posts/{$post->id}");
$this->assertEquals(1, $post->fresh()->views);
}
public function test_can_get_popular_posts(): void
{
$posts = Post::factory()->count(5)->create();
$user = User::factory()->create();
foreach ($posts as $index => $post) {
for ($i = 0; $i <= $index; $i++) {
$post->increment('views');
}
}
$response = $this->actingAs($user)
->getJson('/api/posts/popular');
$response->assertStatus(200)
->assertJsonCount(5, 'data')
->assertJsonPath('data.0.views', 4);
}
}