vendredi 26 janvier 2018

Tests for Event Listeners sendin email

I'm quite new to testing so any help would be appreciated. First things first, this is my code inside App directory (Laravel 5.5)

// controller
public function store(Request $request)
{    
        $foo = new Foo($request->only([
            'value 1', 
            'value 2', 
            'value 3',
        ]));
        $foo->save();

        event(new FooCreated($foo));

        return redirect()->route('/');
}

// Events/FooCreated
use App\Foo;

class FooCreated
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $foo;

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


// Listeners/

use App\Events\FooCreated;
use App\Mail\FooSendingEmail;

class EmailSendListener
{

    /**
     * Handle the event.
     *
     * @param  EnquiryWasCreated  $event
     * @return void
     */
    public function handle(FooCreated $event)
    {
        \Mail::to($event->foo->email)->send(new FooSendingEmail($event->foo));
    }
}

Now, I'm trying to write some tests for the event and the listener that triggers the email to sent, so I have created a method in unit/ExampleTest.php

public function testEventTriggered(){
    Event::fake();

    $foo = factory(\App\Foo::class)->create();

    Event::assertDispatched(FooEvent::class, function($event) use ($foo){
         return $event->foo->id == $foo->id;
    });
}

// assume similar this applies for emails according to docs https://laravel.com/docs/5.5/mocking#mail-fake

but when I run this test, fails with error The expected [App\Events\FooEvent] event was not dispatched. Failed asserting that false is true.

How can I fix the testfor events to pass and also to test sending email ?

Thanks in advance.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire