首页 > 解决方案 > 使用 Event::fake() 或 Queue::fake() 时通知测试失败

问题描述

我为通知创建了一个测试。通知是通过由侦听器处理的事件触发的。当我只使用Notification::fake().

这是我的测试的样子:

Feature\FieldReportTest.php

public function testStoreShouldBeAbleToTagAndNotifyTaggedUsersWhenProvided()
{
    // Queue::fake();
    // Event::fake();
    // Event::assertNotDispatched(UserTagged::class);
    Notification::fake();
    Notification::assertNothingSent();
    // Queue::assertNothingPushed();

    $company = Company::factory()->createOne([
        'user_id' => $this->user->id,
    ]);

    $branch = Branch::factory()->createOne([
        'user_id' => $company->user_id,
        'company_id' => $company->id
    ]);

    $taggedUsers = User::factory(3)->create();

    $new = FieldReport::factory()->makeOne([
        'user_id' => $this->user->id,
        'company_id' => $company->id,
        'branch_id' => $branch->id,
        'tagged_users' => $taggedUsers->pluck('id'),
    ])->toArray();

    $this->actingAs($this->user->assignRole('employee'), 'api')
        ->postJson(route('fieldReports.store'), $new)
        ->assertCreated()
        ->assertJsonFragment($taggedUsers->first()->toArray());

    // Event::assertDispatched(UserTagged::class);
    // Event::assertDispatchedTimes(UserTagged::class, 1);
    // Queue::assertPushed(
    //     CallQueuedListener::class,
    //     fn ($job) => $job->class == SendUserTaggedNotification::class,
    // );
    Notification::assertSentTo($taggedUsers->all(), UserTaggedNotification::class);
    Notification::assertTimesSent(3, UserTaggedNotification::class);
}

当我取消注释Queue::fake();Event::fake().

  • Tests\Feature\FieldReportTest > store should be able to tag and notify tagged users when provided
  The expected [App\Notifications\UserTaggedNotification] notification was not sent.
  Failed asserting that false is true.

我已经用谷歌搜索了类似的问题,并尝试了一些像这个这样的公认答案,但仍然无法使其工作。那么,确保我的应用程序的事件侦听器和队列系统按预期运行的正确方法是什么?我想测试它们,因为它们都是链接的。

更新

也许提供的信息不足以复制问题。为了清楚通知是如何发送的,这里我提供了发送事件的脚本,请看一下..

Models\FieldReport.php

/**
 * Register new data given by the client.
 *
 * @param array $data
 * @return FieldReport
 */
public function register($data)
{
    $data = collect($data);
    $registry = $data->except(['images', 'tagged_users'])->toArray();
    $registry = request()->user()->fieldReports()->create($registry);

    $this->storeImages($registry, $data);
    $this->assignAndNotifyTaggedUsers($registry, $data);
    return $registry->load('author', 'images', 'taggedUsers');
}

/**
 * Store images and attach relationships for each images.
 *
 * @param \App\Models\FieldReport $registry
 * @param \Illuminate\Support\Collection $data
 * @return void
 */
public function storeImages($registry, $data)
{
    ... // irrelevant
}

/**
 * Assign tagged users into registry and let them know
 * that they are tagged by the author.
 *
 * @param \App\Models\FieldReport $registry
 * @param \Illuminate\Support\Collection $data
 * @return void
 */
public function assignAndNotifyTaggedUsers($registry, $data)
{
    if ($registry && $data->has('tagged_users')) {
        $tagged = $registry->taggedUsers()->sync(
            $data->get('tagged_users')
        );

        if (collect($tagged)->isNotEmpty()) {
            UserTagged::dispatch($registry, 'Field Report');
        }
    }
}

Events\UserTagged.php

class UserTagged
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $model;
    public $subject;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($model, $subject)
    {
        $this->model = $model;
        $this->subject = $subject;
    }
}

Listeners\SendUserTaggedNotification.php

class SendUserTaggedNotification implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * Handle the event.
     *
     * @param  UserTagged  $event
     * @return void
     */
    public function handle(UserTagged $event)
    {
        $event->model->taggedUsers->each(
            fn ($user) => $user->notify(
                new UserTaggedNotification($event->model, $event->subject)
            )
        );
    }
}

标签: laravel

解决方案


推荐阅读