Skip to content

Commit

Permalink
Add withoutDefer and withDefer testing helpers (#53340)
Browse files Browse the repository at this point in the history
  • Loading branch information
timacdonald authored Oct 30, 2024
1 parent 17acf83 commit fa1f4ca
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Closure;
use Illuminate\Foundation\Mix;
use Illuminate\Foundation\Vite;
use Illuminate\Support\Defer\DeferredCallbackCollection;
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\HtmlString;
use Mockery;
Expand All @@ -25,6 +26,13 @@ trait InteractsWithContainer
*/
protected $originalMix;

/**
* The original deferred callbacks collection.
*
* @var \Illuminate\Support\Defer\DeferredCallbackCollection|null
*/
protected $originalDeferredCallbacksCollection;

/**
* Register an instance of an object in the container.
*
Expand Down Expand Up @@ -234,4 +242,38 @@ protected function withMix()

return $this;
}

/**
* Execute deferred functions immediately.
*
* @return $this
*/
protected function withoutDefer()
{
if ($this->originalDeferredCallbacksCollection == null) {
$this->originalDeferredCallbacksCollection = $this->app->make(DeferredCallbackCollection::class);
}

$this->swap(DeferredCallbackCollection::class, new class extends DeferredCallbackCollection
{
public function offsetSet(mixed $offset, mixed $value): void
{
$value();
}
});
}

/**
* Restore deferred functions.
*
* @return $this
*/
protected function withDefer()
{
if ($this->originalDeferredCallbacksCollection) {
$this->app->instance(DeferredCallbackCollection::class, $this->originalDeferredCallbacksCollection);
}

return $this;
}
}
21 changes: 21 additions & 0 deletions tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Foundation\Mix;
use Illuminate\Foundation\Vite;
use Illuminate\Support\Defer\DeferredCallbackCollection;
use Orchestra\Testbench\TestCase;
use stdClass;

Expand Down Expand Up @@ -73,6 +74,26 @@ public function testWithMixRestoresOriginalHandlerAndReturnsInstance()
$this->assertSame($this, $instance);
}

public function testWithoutDefer()
{
$called = [];
defer(function () use (&$called) {
$called[] = 1;
});
$this->assertSame([], $called);

$this->withoutDefer();
defer(function () use (&$called) {
$called[] = 2;
});
$this->assertSame([2], $called);

$this->withDefer();
$this->assertSame([2], $called);
$this->app[DeferredCallbackCollection::class]->invoke();
$this->assertSame([2, 1], $called);
}

public function testForgetMock()
{
$this->mock(InstanceStub::class)
Expand Down

0 comments on commit fa1f4ca

Please sign in to comment.