Laravel Notification断言将数据传递到邮件markdown视图

I am working on a Laravel project. I am writing integration/ feature tests for my application. I am now writing a test where I need to assert the data passed to the email notification and the data passed to its view. I found this link to do it, https://medium.com/@vivekdhumal/how-to-test-mail-notifications-in-laravel-345528917494.

这是我的通知课

class NotifyAdminForHelpCenterCreated extends Notification
{
    use Queueable;

    private $helpCenter;

    public function __construct(HelpCenter $helpCenter)
    {
        $this->helpCenter = $helpCenter;
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage())
            ->subject("Help Center registration")
            ->markdown('mail.admin.helpcenter.created-admin', [
                'helpCenter' => $this->helpCenter,
                'user' => $notifiable
            ]);
    }
}

如您在代码中看到的,我正在将数据传递到mail.admin.helpcenter.created-admin刀片视图。

这是我的测试方法。

/** @test */
public function myTest()
{
    $body = $this->requestBody();
    $this->actingAsSuperAdmin()
        ->post(route('admin.help-center.store'), $body)
        ->assertRedirect();

    $admin = User::where('email', $body['admin_email'])->first();
    $helpCenter = HelpCenter::first();

    Notification::assertSentTo(
        $admin,
        NotifyAdminForHelpCenterCreated::class,
        function ($notification, $channels) use ($admin, $helpCenter) {
            $mailData = $notification->toMail($admin)->toArray();
            //here I can do some assertions with the $mailData
            return true;
        }
    );
}

您可以在测试中看到我的评论,我可以使用$ mailData变量进行一些断言。但这不包括传递给视图的数据。如何断言或获取传递到刀片视图/模板的数据或变量?

评论
  • nsunt
    nsunt 回复

    As you can see here, there is a viewData property on the MailMessage class which contains all the data passed to the view, no need to turn the notification into an array.

    $notification->toMail($admin)->viewData
    

    因此,在您的情况下将是这样的:

    /** @test */
    public function myTest()
    {
        $body = $this->requestBody();
        $this->actingAsSuperAdmin()
            ->post(route('admin.help-center.store'), $body)
            ->assertRedirect();
    
        $admin = User::where('email', $body['admin_email'])->first();
        $helpCenter = HelpCenter::first();
    
        Notification::assertSentTo(
            $admin,
            NotifyAdminForHelpCenterCreated::class,
            function ($notification, $channels) use ($admin, $helpCenter) {
                $viewData = $notification->toMail($admin)->viewData;
    
                return $admin->is($viewData['user']) && $helpCenter->is($viewData['helpCenter']);
            }
        );
    }