0

I am developing a Laravel application and doing the unit test. Now, I am having a bit of an issue with faking and un-faking Laravel event in the unit test. What I am trying to do is something like this.

public function test_something()
{
     Event::fake();
     //Do somethng
     //Then I want to stop faking event here something like this
     Event::stopFaking(); //maybe
}

I think my code is self-explanatory. How can I achieve something like that in Laravel?

Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

2 Answers2

2

https://laravel.com/docs/5.7/mocking

If you only want to fake event listeners for a portion of your test, you may use the fakeFor method:

    $order = Event::fakeFor(function () {
        $order = factory(Order::class)->create();

        Event::assertDispatched(OrderCreated::class);

        return $order;
    });

    // Events are dispatched as normal and observers will run ...
    $order->update([...]);

Everything inside the function() {} will have faked events. Everything outside will function normally.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
1

The Event::fake function is defined in Illuminate\Support\Facades\Event.

We can see that there is a fakeFor method that only fakes it during the execution of a callback method, then restores the original behavior. You can use it like this:

public function test_something()
{
     Event::fakeFor(function () {
         //Do somethng
     });
}

As a Laravel developer it is often useful to read the source code, there are lots of nice bits and pieces in this framework that are not documented!

Emil Vikström
  • 90,431
  • 16
  • 141
  • 175