From 8788a335193237e080611d2c370c8d6c6129a768 Mon Sep 17 00:00:00 2001 From: Caleb Porzio Date: Thu, 1 Oct 2020 14:30:48 -0400 Subject: [PATCH] Allow asserting has errors on custom validator errors --- src/Testing/Concerns/MakesAssertions.php | 8 ++++++-- src/Testing/TestableLivewire.php | 6 ++++++ tests/Unit/ValidationTest.php | 13 +++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/Testing/Concerns/MakesAssertions.php b/src/Testing/Concerns/MakesAssertions.php index 857455506..0a6892190 100644 --- a/src/Testing/Concerns/MakesAssertions.php +++ b/src/Testing/Concerns/MakesAssertions.php @@ -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.'); @@ -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()) . '"'); diff --git a/src/Testing/TestableLivewire.php b/src/Testing/TestableLivewire.php index 0bc7d9649..6cf141a56 100644 --- a/src/Testing/TestableLivewire.php +++ b/src/Testing/TestableLivewire.php @@ -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; }); diff --git a/tests/Unit/ValidationTest.php b/tests/Unit/ValidationTest.php index ad898201f..b623c4433 100644 --- a/tests/Unit/ValidationTest.php +++ b/tests/Unit/ValidationTest.php @@ -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 @@ -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');