Skip to content

Commit

Permalink
Allow asserting has errors on custom validator errors
Browse files Browse the repository at this point in the history
  • Loading branch information
calebporzio committed Oct 1, 2020
1 parent 9867969 commit 8788a33
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Testing/Concerns/MakesAssertions.php
Expand Up @@ -189,7 +189,9 @@ public function assertDispatchedBrowserEvent($name, $data = null)

public function assertHasErrors($keys = [])
{
$errors = new MessageBag($this->payload['serverMemo']['errors'] ?: []);
$errors = new MessageBag(
$this->lastValidator->errors()->messages()
);

PHPUnit::assertTrue($errors->isNotEmpty(), 'Component has no errors.');

Expand All @@ -213,7 +215,9 @@ public function assertHasErrors($keys = [])

public function assertHasNoErrors($keys = [])
{
$errors = new MessageBag($this->payload['serverMemo']['errors'] ?? []);
$errors = new MessageBag(
$this->lastValidator ? $this->lastValidator->errors()->messages() : []
);

if (empty($keys)) {
PHPUnit::assertTrue($errors->isEmpty(), 'Component has errors: "' . implode('", "', $errors->keys()) . '"');
Expand Down
6 changes: 6 additions & 0 deletions src/Testing/TestableLivewire.php
Expand Up @@ -40,6 +40,12 @@ public function __construct($name, $params = [])
$this->lastValidator = $validator;
});

Livewire::listen('component.hydrate.subsequent', function ($validator) {
// Clear the validator held in memory from the last request so we
// can properly assert validation errors for the most recent request.
$this->lastValidator = null;
});

Livewire::listen('component.dehydrate', function($component) {
static::$instancesById[$component->id] = $component;
});
Expand Down
13 changes: 13 additions & 0 deletions tests/Unit/ValidationTest.php
Expand Up @@ -362,6 +362,14 @@ public function only_data_in_validation_rules_is_returned()
'bar' => $component->bar,
], $validatedData);
}

/** @test */
public function can_assert_validation_errors_on_errors_thrown_from_custom_validator()
{
$component = Livewire::test(ForValidation::class);

$component->call('failFooOnCustomValidator')->assertHasErrors('plop');
}
}

class ForValidation extends Component
Expand Down Expand Up @@ -508,6 +516,11 @@ public function runValidationWithoutAllPublicPropertiesAndReturnValidatedData()
return $this->validate(['bar' => 'required']);
}

public function failFooOnCustomValidator()
{
Validator::make([], ['plop' => 'required'])->validate();
}

public function render()
{
return app('view')->make('dump-errors');
Expand Down

0 comments on commit 8788a33

Please sign in to comment.