Skip to content

Commit

Permalink
Adding tests for the Notification service
Browse files Browse the repository at this point in the history
  • Loading branch information
amitavroy committed Dec 24, 2024
1 parent 55d4df0 commit 2f2dc78
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 1 deletion.
5 changes: 5 additions & 0 deletions app/Domain/Notification/Models/Notification.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ class Notification extends Model
/** @use HasFactory<NotificationFactory> */
use HasFactory;

protected static function newFactory(): NotificationFactory
{
return NotificationFactory::new();
}

protected $fillable = ['title', 'message'];

/**
Expand Down
2 changes: 1 addition & 1 deletion app/Domain/Notification/Services/NotificationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public function getUserUnreadNotifications(User $user): LengthAwarePaginator
->where('user_notification.user_id', '=', $user->id);
})
->whereNull('user_notification.id')
->select(['notifications.id', 'notifications.'])
->select(['notifications.id', 'notifications.title', 'notifications.message'])
->paginate(10);
}
}
2 changes: 2 additions & 0 deletions database/factories/NotificationFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
*/
class NotificationFactory extends Factory
{
protected $model = Notification::class;

/**
* Define the model's default state.
*
Expand Down
42 changes: 42 additions & 0 deletions tests/Feature/Services/NotificationServiceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

use Illuminate\Pagination\LengthAwarePaginator;
use App\Domain\Notification\Models\Notification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Domain\Notification\Services\NotificationService;

uses(RefreshDatabase::class);

describe('NotificationService test', function () {
it('returns a paginated data list', function () {
$user = \App\Models\User::factory()->create();

Notification::factory(5)->create();

$service = app(NotificationService::class);

$service->getUserUnreadNotifications($user);

expect($service->getUserUnreadNotifications($user))
->toBeInstanceOf(LengthAwarePaginator::class);
});

it('returns only the unread notifications', function () {
$user = \App\Models\User::factory()->create();

$notification = Notification::factory()->create();
Notification::factory()->create();

DB::table('user_notification')->insert([
'user_id' => $user->id,
'notification_id' => $notification->id,
'read_at' => now(),
]);

$service = app(NotificationService::class);

$notifications = $service->getUserUnreadNotifications($user);

expect($notifications->total())->toBe(1);
});
});

0 comments on commit 2f2dc78

Please sign in to comment.