Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add Event::fakeExcept() to fake all but certain events #39752

Merged
merged 2 commits into from Nov 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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