Skip to content

Commit

Permalink
[9.x] Add view data assertions to TestView (#43923)
Browse files Browse the repository at this point in the history
* add view data assertions to `TestView`

- `assertViewHas()`
- `assertViewHasAll()`
- `assertViewMissing()`

these methods are all available on the `TestResponse`, but not currently `TestView`.  These assertions can be more helpful to test the workings of the component, and not reliant on how the data actually gets displayed on the view side of things.

* Update TestView.php

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
browner12 and taylorotwell authored Aug 30, 2022
1 parent 0ec2c41 commit e07e005
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/Illuminate/Testing/TestView.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

namespace Illuminate\Testing;

use Closure;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Testing\Assert as PHPUnit;
use Illuminate\Testing\Constraints\SeeInOrder;
Expand Down Expand Up @@ -37,6 +41,71 @@ public function __construct(View $view)
$this->rendered = $view->render();
}

/**
* Assert that the response view has a given piece of bound data.
*
* @param string|array $key
* @param mixed $value
* @return $this
*/
public function assertViewHas($key, $value = null)
{
if (is_array($key)) {
return $this->assertViewHasAll($key);
}

if (is_null($value)) {
PHPUnit::assertTrue(Arr::has($this->view->gatherData(), $key));
} elseif ($value instanceof Closure) {
PHPUnit::assertTrue($value(Arr::get($this->view->gatherData(), $key)));
} elseif ($value instanceof Model) {
PHPUnit::assertTrue($value->is(Arr::get($this->view->gatherData(), $key)));
} elseif ($value instanceof Collection) {
$actual = Arr::get($this->view->gatherData(), $key);

PHPUnit::assertInstanceOf(Collection::class, $actual);
PHPUnit::assertSameSize($value, $actual);

$value->each(fn ($item, $index) => PHPUnit::assertTrue($actual->get($index)->is($item)));
} else {
PHPUnit::assertEquals($value, Arr::get($this->view->gatherData(), $key));
}

return $this;
}

/**
* Assert that the response view has a given list of bound data.
*
* @param array $bindings
* @return $this
*/
public function assertViewHasAll(array $bindings)
{
foreach ($bindings as $key => $value) {
if (is_int($key)) {
$this->assertViewHas($value);
} else {
$this->assertViewHas($key, $value);
}
}

return $this;
}

/**
* Assert that the response view is missing a piece of bound data.
*
* @param string $key
* @return $this
*/
public function assertViewMissing($key)
{
PHPUnit::assertFalse(Arr::has($this->view->gatherData(), $key));

return $this;
}

/**
* Assert that the given string is contained within the view.
*
Expand Down

0 comments on commit e07e005

Please sign in to comment.