NovinkaZverejnili sme 50+ Laravel balíkov ako open source
Custom AI apps, agents and automation — Roundly ConsultingRoundly
Všetky balíky

Notifications::fake() vymení manažéra za NotificationsFake za fasádou aj v kontajneri a vráti ho:

use RoundlyConsulting\Notifications\Facades\Notifications;

it('asks the approvers', function (): void {
    $notifications = Notifications::fake();            // record-only: nothing is written, nothing is mailed
    $request = PurchaseRequest::factory()->create();

    $this->actingAs($request->author)->post("/requests/{$request->id}/submit")->assertRedirect();

    $notifications->assertSent(RequestAwaitingApproval::class, to: $approver, about: $request);   // key or class
    $notifications->assertNotSent('request.awaiting_approval', to: $request->author);
    $notifications->assertNotSent('security.alert');
});
  • Len zaznamenáva: každé meniace volanie — odoslania (aj cez type()->…->send(), for()->send() a sendNotification()), zmeny schránky, zápisy preferencií, uplatnenia odkazov na odhlásenie, schedule / sync / remind / cancel / snooze / acknowledge pripomienok, revoke, sweepy, prune, kanál inbox, vyčistenie schránky po zmazanom subjekte aj volania cez traity modelov — sa zaznamená a nevykoná. Odoslanie pod fake vráti SendResult s kľúčom druhu a bez výsledkov, ako skutočné odoslanie.
  • Odoslanie stále prejde kontrolami, ktoré skutočné odoslanie robí vopred, a vyhodí rovnaké výnimky bez záznamu: neznámy druh, subjekt nesprávnej triedy alebo eskalácia bez subjektu, dáta, ktoré nie sú čistý JSON, zlé kľúče, kontexty či neuložiteľní príjemcovia eskalácie — zelený test nikdy neskryje výnimku z produkcie.
  • Čítanie (inbox()->paginate(), types(), preferences()->matrix()) ide do skutočného úložiska a registrácia druhov prebehne normálne.
  • Vyhodnotenie príjemcov stále beží, takže assertSent(to: $user) funguje aj s Recipients::role(). Kontroly prístupu, preferencie, tiché hodiny ani deduplikácia nebežia: asercia dokazuje zámer upozorniť, nie doručenie.
  • NotificationsFake rozširuje manažéra, takže aj injektovaný NotificationsManager je fake a prejde typovou kontrolou. Priame volanie akcie sa nezaznamená.
  • Interop listener fake nikdy nezaznamená ani nezablokuje.
  • ->passthrough() zaznamená a zároveň vykoná každú operáciu.
  • ->withReminders() (od 1.3.0) vykoná operácie pripomienok naozaj — schedule, sync, remind(), cancel, snooze, acknowledge, backfill, odoslanie — takže riadky pripomienok existujú a odchádzajú, no odoslania, ktoré vyvolajú, sa len zaznamenajú. Odoslania pripomienok a eskalácií idú cez manažéra, takže ich fake zaznamená ako každé iné odoslanie.
Notifications::fake();

// The real send's up-front checks still run — and throw the same exceptions, recording nothing
Notifications::send('request.awaitng_approval', $request, $approver);   // UnknownNotificationTypeException
Notifications::send('security.alert', $request, $user);                 // InvalidNotificationSubjectException: no subject expected
Notifications::send('comment.posted', $post, $user, ['post' => $post]); // InvalidNotificationDataException: not plain JSON

Asercie

Každá asercia je na fake a fasáda ju preposiela; pri zlyhaní uvedie, čo očakávala. Každá asercia s druhom prijme kľúč druhu aj jeho triedu a fake zaznamená druh každej operácie ako kľúč, tak ako ho ukladajú skutočné operácie — remind(Foo::class, …) teda prejde cez assertReminderScheduled($subject, 'foo.key') a naopak:

AserciaPrejde, keď
assertSent($type, to: ?Model|Closure, about: ?Model, times: ?int)Bolo zaznamenané odoslanie druhu (príjemcovi, o subjekte; presne times-krát). Closure v to dostane každého vyhodnoteného príjemcu.
assertNotSent($type, to: ?Model|Closure, about: ?Model)Žiadne také odoslanie — tomu príjemcovi, o tom subjekte.
assertNothingSent()Žiadne odoslanie vôbec.
assertMarkedRead(?Model $recipient) · assertNothingMarkedRead()markRead() alebo markAllRead() / žiadne.
assertMarkedUnread(?Model $recipient)markUnread().
assertArchived(?Model $recipient) · assertNothingArchived()archive() / žiadne.
assertUnarchived(?Model $recipient)unarchive().
assertDeleted(?Model $recipient)delete().
assertInboxMessage(Model $recipient, ?string $type)Kanál inbox z Laravelu zapísal správu (daného druhu).
assertSubjectForgotten(Model $subject)Prebehlo vyčistenie schránky po zmazanom subjekte (notifications.inbox.on_subject_deleted nie je keep).
assertPreferenceSet($user, $type, Channel $channel, bool $enabled)set() alebo mute() daného kanála na danú hodnotu.
assertMuted($user, $type)Stlmenie (vypnutie) druhu.
assertCategoryPreferenceSet($user, $category, Channel $channel, ?bool $enabled)muteCategory() (false) alebo unmuteCategory() (null).
assertPreferencesUpdated($user, ?Closure $where)preferences($user)->update(); $where(PreferencesUpdate): bool ho zúži.
assertPreferencesReset($user)reset().
assertDigestSet($user, DigestFrequency $frequency, ?string $time)digest(); čas null zodpovedá akémukoľvek času.
assertQuietHoursSet($user, ?string $start, ?string $end)quietHours(); oba null: zrušené.
assertTimezoneSet($user, ?string $timezone)timezone(); null: zrušené.
assertUnsubscribed(?Model $recipient, ?string $type) · assertNothingUnsubscribed()unsubscribe()->redeem($token) — zaznamená sa príjemca a druh z odkazu; zlý token vyhodí výnimku ako v produkcii / žiadne.
assertNoPreferenceChanged()Žiadny zápis preferencií akéhokoľvek druhu — druh, kategória, reset, update, súhrn, tiché hodiny, časové pásmo.
assertRemindersSynced($subject)Synchronizácia vrátane tej, ktorú HasNotificationReminders spustí pri uložení.
assertReminderScheduled($subject, $type, ?bool $restart = null)schedule() alebo remind(); restart: true zodpovedá len schedule(…, restart: true), false len volaniu bez neho.
assertNoRemindersScheduled()Žiadne schedule(), sync, remind() ani backfill.
assertRemindersCancelled($subject, ?Model $for = null)cancel() alebo zrušenie, ktoré spustí zmazanie subjektu; s for: len cancel(for: $recipient) daného príjemcu.
assertRemindersSnoozed($subject, ?Model $recipient, ?$type, ?CarbonInterface $until)reminders()->snooze() (od 1.4.0).
assertAcknowledged($subject, ?$type)acknowledge().
fireDueReminders(): FiredRemindersNie je asercia: hneď spustí krok pripomienok zo sweepu (aj bez withReminders()); odoslania, ktoré vyvolá, sa zaznamenajú.
assertReminded(Model $recipient, string $type, ?int $times, ?Model $about) · assertNotReminded($recipient, $type, ?$about)Odoslaná pripomienka poslala druh príjemcovi (bez eskalácií) / žiadna.
assertEscalated(string $type, ?Model $to, ?int $times, ?Model $about)Spustila sa eskalácia.
assertRevoked($subject, ?Model $recipient)revoke().
assertSwept() · assertPruned()sweep() alebo notifications:sweep / prune() alebo notifications:prune.
assertRecorded(NotificationOperation $operation, ?Closure $where, ?int $times)Akákoľvek operácia — aj tie bez pomenovanej asercie (SendDigests, DispatchDeliveries, FireReminders, BackfillReminders); $where(RecordedOperation): bool ju zúži.
assertNotRecorded(NotificationOperation $operation, ?Closure $where)Žiadna taká operácia.
$fake = Notifications::fake();

$fake->assertSent('comment.posted', to: fn (User $user): bool => $user->is_admin, times: 2);
$fake->assertNotSent('comment.posted', about: $draft);
$fake->assertMarkedRead($user);
$fake->assertDeleted($user);
$fake->assertInboxMessage($user, 'comment.posted');
$fake->assertDigestSet($user, DigestFrequency::Daily);          // any time
$fake->assertQuietHoursSet($user, '22:00', '07:00');
$fake->assertPreferencesUpdated($user, fn (PreferencesUpdate $update): bool => isset($update->channels['comment.posted']));
$fake->assertRemindersSynced($contract);                        // also the sync HasNotificationReminders runs on save
$fake->assertAcknowledged($contract, 'contract.expiring');
$fake->assertRevoked($request, $formerMember);
$fake->assertSubjectForgotten($post);                           // the on_subject_deleted cleanup of a deleted subject
$fake->assertUnsubscribed($user, 'comment.posted');             // a redeemed one-click unsubscribe link
$fake->assertSwept();

// Operations without a named assertion
$fake->assertRecorded(NotificationOperation::SendDigests);
$fake->assertRecorded(NotificationOperation::Send, fn (RecordedOperation $op): bool => $op->subject?->is($request) ?? false, times: 1);
$fake->assertNotRecorded(NotificationOperation::BackfillReminders);

// The facade forwards every assertion too
Notifications::assertNothingSent();
Notifications::assertNoPreferenceChanged();

// Record and still run
Notifications::fake()->passthrough();

Testovanie opakovaných pripomienok

Spojte withReminders() s posunom času a fireDueReminders() a potom overte výsledok pre každého príjemcu:

$fake = Notifications::fake()->withReminders();
Notifications::for($policy)->reminders()->schedule('policy.unacknowledged', to: [$jane, $john]);

$this->travel(7)->days();
$fake->fireDueReminders();
Notifications::for($policy)->acknowledge('policy.unacknowledged', by: $jane);
$this->travel(7)->days();
$fake->fireDueReminders();

$fake->assertReminded($jane, 'policy.unacknowledged', times: 1);
$fake->assertReminded($john, 'policy.unacknowledged', times: 2);

Zaznamenané operácie

$fake->recorded(?NotificationOperation $operation = null) vráti záznamy RecordedOperation v poradí volaní — operation, context (argumenty volania), vyhodnotených príjemcov odoslania, type a subject:

use RoundlyConsulting\Notifications\Enums\NotificationOperation;

foreach ($fake->recorded(NotificationOperation::Send) as $send) {
    $send->operation;     // NotificationOperation::Send
    $send->type;          // 'request.awaiting_approval'
    $send->subject;       // the subject model
    $send->recipients;    // list<Model> — the resolved recipients
    $send->context;       // the call's arguments
}

Pest expectations

Registrujú sa automaticky cez Pest plugin balíka a čítajú databázu:

ExpectationPrejde, keď
toHaveUnreadInboxItems(int $count)Presne toľko neprečítaných, nearchivovaných položiek.
toHaveInboxItem(string $type, ?Model $subject = null)Položka daného druhu (o subjekte).
toHaveMuted(string $type)E-mail druhu je pre používateľa vypnutý.
expect($user)->toHaveUnreadInboxItems(1);
expect($user)->toHaveInboxItem('request.awaiting_approval', $request);
expect($user)->toHaveMuted('comment.posted');

// Where Pest plugin discovery is off
RoundlyConsulting\Notifications\Testing\NotificationExpectations::register();

Skutočný postup s Notification::fake()

Ak chcete overiť doručenie, spustite skutočný postup a fake použite na notifikácie Laravelu. Súhrny prichádzajú ako DigestMailNotification. Pri tichých hodinách, súhrnoch a pripomienkach zmrazte čas a splatné veci uvoľnite cez Notifications::sweep():

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Notification;
use RoundlyConsulting\Notifications\Mail\TypedMailNotification;

Notification::fake();

Notifications::send('security.alert', null, $user);

Notification::assertSentTo($user, TypedMailNotification::class, fn ($n) => $n->type === 'security.alert');
expect($user)->toHaveUnreadInboxItems(1);

// Quiet hours, digests and reminders: freeze time, then release what is due
Carbon::setTestNow('2026-11-10 07:01');
Notifications::sweep();

Notification::fake() nespúšťa NotificationSending, takže pod ním interop nebeží.

Factories

Každý model má factory, ktorá rešpektuje vymenený model:

InboxItem::factory()->recipient($user)->read()->create();
NotificationDelivery::factory()->recipient($user)->status(DeliveryStatus::Held)->create();
NotificationReminder::factory()->subject($contract)->create();
DigestRun::factory()->recipient($user)->create();
NotificationReceipt::factory()->create();

Testovanie aplikácie

  • Publikujte obe sady migrácií (notifications aj options) — RefreshDatabase v testoch funguje na SQLite.
  • Pre každú triedu subjektu, ktorú vaše druhy používajú, definujte policy alebo oprávnenie view, inak prvé odoslanie vyhodí MissingAccessCheckException.
  • Ak test potrebuje, aby e-mail odišiel priamo, vypnite front (alebo použite spojenie sync).
  • V phpunit.xml používajte hodnoty on / off:
<php>
    <env name="NOTIFICATIONS_ROUTES_ENABLED" value="on"/>
    <env name="NOTIFICATIONS_QUEUE_ENABLED" value="off"/>
</php>

Prejavte lásku k open source

Tento balík je zadarmo pod licenciou MIT. Ak vám šetrí čas, jednorazový príspevok alebo členstvo na Patreone nám pomôže ho ďalej udržiavať, testovať a dokumentovať.

Ďalšie spôsoby podpory vrátane kryptomien

Odoslaním daru súhlasíte s našimi podmienkami prijímania darov.

Chcete to zabudovať do svojho produktu?

Naše balíky integrujeme do zákazkových Laravel a AI riešení. Napíšte nám, na čom pracujete, a ozveme sa do 48 hodín.