From 7bea51fe09dd2eca7093e4c34cf2dab2e8d39fa5 Mon Sep 17 00:00:00 2001 From: Nuno Maduro Date: Mon, 23 Nov 2020 21:26:02 +0100 Subject: [PATCH] feat: adds `toMatchArray` --- src/Expectation.php | 25 +++++++++++++++++++++++-- tests/.snapshots/success.txt | 7 ++++++- tests/Expect/toMatchArray.php | 31 +++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 tests/Expect/toMatchArray.php diff --git a/src/Expectation.php b/src/Expectation.php index 3b60d52d..00f87ffd 100644 --- a/src/Expectation.php +++ b/src/Expectation.php @@ -408,10 +408,17 @@ final class Expectation * Asserts that the value array has the provided $key. * * @param string|int $key + * @param mixed $value */ - public function toHaveKey($key): Expectation + public function toHaveKey($key, $value = null): Expectation { - Assert::assertArrayHasKey($key, $this->value); + $array = (array) $this->value; + + Assert::assertArrayHasKey($key, $array); + + if (func_num_args() > 1) { + Assert::assertEquals($value, $array[$key]); + } return $this; } @@ -490,6 +497,20 @@ final class Expectation return $this; } + /** + * Asserts that the value array matches the given array subset. + * + * @param array $array + */ + public function toMatchArray($array): Expectation + { + foreach ($array as $property => $value) { + $this->toHaveKey($property, $value); + } + + return $this; + } + /** * Asserts that the value object matches a subset * of the properties of an given object. diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index 3a5ea963..300d25c6 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -200,6 +200,11 @@ PASS Tests\Expect\toMatch ✓ pass ✓ failures + ✓ not failures + + PASS Tests\Expect\toMatchArray + ✓ pass + ✓ failures ✓ not failures PASS Tests\Expect\toMatchConstraint @@ -399,5 +404,5 @@ ✓ depends run test only once ✓ depends works with the correct test name - Tests: 7 skipped, 235 passed + Tests: 7 skipped, 238 passed \ No newline at end of file diff --git a/tests/Expect/toMatchArray.php b/tests/Expect/toMatchArray.php new file mode 100644 index 00000000..b1646b9e --- /dev/null +++ b/tests/Expect/toMatchArray.php @@ -0,0 +1,31 @@ +user = [ + 'id' => 1, + 'name' => 'Nuno', + 'email' => 'enunomaduro@gmail.com', + ]; +}); + +test('pass', function () { + expect($this->user)->toMatchArray([ + 'name' => 'Nuno', + 'email' => 'enunomaduro@gmail.com', + ]); +}); + +test('failures', function () { + expect($this->user)->toMatchArray([ + 'name' => 'Not the same name', + 'email' => 'enunomaduro@gmail.com', + ]); +})->throws(ExpectationFailedException::class); + +test('not failures', function () { + expect($this->user)->not->toMatchArray([ + 'id' => 1, + ]); +})->throws(ExpectationFailedException::class);