Skip to content

Commit

Permalink
[8.x] Add Event::fakeExcept() to fake all but certain events (#39752)
Browse files Browse the repository at this point in the history
* Add Event::fakeExcept() to fake all but certain events

* formatting

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
devfrey and taylorotwell committed Nov 25, 2021
1 parent c978893 commit a8b9642
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/Illuminate/Support/Facades/Event.php
Expand Up @@ -45,6 +45,21 @@ public static function fake($eventsToFake = [])
return $fake;
}

/**
* Replace the bound instance with a fake that fakes all events except the given events.
*
* @param string[]|string $eventsToAllow
* @return \Illuminate\Support\Testing\Fakes\EventFake
*/
public static function fakeExcept($eventsToAllow)
{
return static::fake([
function ($eventName) use ($eventsToAllow) {
return ! in_array($eventName, (array) $eventsToAllow);
},
]);
}

/**
* Replace the bound instance with a fake during the given callable's execution.
*
Expand All @@ -66,6 +81,27 @@ public static function fakeFor(callable $callable, array $eventsToFake = [])
});
}

/**
* Replace the bound instance with a fake during the given callable's execution.
*
* @param callable $callable
* @param array $eventsToAllow
* @return mixed
*/
public static function fakeExceptFor(callable $callable, array $eventsToAllow = [])
{
$originalDispatcher = static::getFacadeRoot();

static::fakeExcept($eventsToAllow);

return tap($callable(), function () use ($originalDispatcher) {
static::swap($originalDispatcher);

Model::setEventDispatcher($originalDispatcher);
Cache::refreshEventDispatcher();
});
}

/**
* Get the registered name of the component.
*
Expand Down
23 changes: 23 additions & 0 deletions tests/Integration/Events/EventFakeTest.php
Expand Up @@ -98,6 +98,29 @@ public function testNonFakedHaltedEventGetsProperlyDispatchedAndReturnsResponse(
Event::assertNotDispatched(NonImportantEvent::class);
}

public function testFakeExceptAllowsGivenEventToBeDispatched()
{
Event::fakeExcept(NonImportantEvent::class);

Event::dispatch(NonImportantEvent::class);

Event::assertNotDispatched(NonImportantEvent::class);
}

public function testFakeExceptAllowsGivenEventsToBeDispatched()
{
Event::fakeExcept([
NonImportantEvent::class,
'non-fake-event',
]);

Event::dispatch(NonImportantEvent::class);
Event::dispatch('non-fake-event');

Event::assertNotDispatched(NonImportantEvent::class);
Event::assertNotDispatched('non-fake-event');
}

public function testAssertListening()
{
Event::fake();
Expand Down

0 comments on commit a8b9642

Please sign in to comment.