UserNotificationControllerTest.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Tests\Feature;
  3. use App\Models\User;
  4. use App\Models\UserNotification;
  5. use Illuminate\Foundation\Testing\RefreshDatabase;
  6. use Tests\TestCase;
  7. class UserNotificationControllerTest extends TestCase
  8. {
  9. use RefreshDatabase;
  10. public function test_user_can_mark_all_own_notifications_as_read(): void
  11. {
  12. $user = User::factory()->create();
  13. $otherUser = User::factory()->create();
  14. $unreadNotifications = collect([
  15. $this->createNotification($user->id),
  16. $this->createNotification($user->id),
  17. ]);
  18. $alreadyReadAt = now()->subDay();
  19. $alreadyReadNotification = $this->createNotification($user->id, $alreadyReadAt);
  20. $otherUserNotification = $this->createNotification($otherUser->id);
  21. $response = $this->actingAs($user)->postJson(route('notifications.read-all'));
  22. $response
  23. ->assertOk()
  24. ->assertJson([
  25. 'ok' => true,
  26. 'updated' => 2,
  27. 'unread' => 0,
  28. ]);
  29. foreach ($unreadNotifications as $notification) {
  30. $this->assertNotNull($notification->fresh()->read_at);
  31. }
  32. $this->assertSame(
  33. $alreadyReadAt->format('Y-m-d H:i:s'),
  34. $alreadyReadNotification->fresh()->read_at?->format('Y-m-d H:i:s')
  35. );
  36. $this->assertNull($otherUserNotification->fresh()->read_at);
  37. }
  38. private function createNotification(int $userId, $readAt = null): UserNotification
  39. {
  40. return UserNotification::query()->create([
  41. 'user_id' => $userId,
  42. 'type' => UserNotification::TYPE_PLATFORM,
  43. 'event' => UserNotification::EVENT_CREATED,
  44. 'title' => 'Тестовое уведомление',
  45. 'message' => 'Тестовое сообщение',
  46. 'message_html' => '<p>Тестовое сообщение</p>',
  47. 'read_at' => $readAt,
  48. ]);
  49. }
  50. }