Skip to content

Commit

Permalink
fix: Json::assertMissing/assertHas better handle empty-ish values (#116)
Browse files Browse the repository at this point in the history
* assertMissing and assertHas better handle empty-ish values

* Update assertMissing and assertHas to cover more cases

* Remove commented tests and dump
  • Loading branch information
flohw committed Jan 22, 2023
1 parent 456129c commit f4596c8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 12 deletions.
26 changes: 14 additions & 12 deletions src/Browser/Json.php
Expand Up @@ -69,11 +69,13 @@ public function assertMatches(string $expression, $expected): self
*/
public function assertHas(string $selector): self
{
Assert::try(
fn() => $this->search("length({$selector})"),
'Element with selector "{selector}" not found.',
['selector' => $selector]
);
$prefix = 1 === preg_match('#^\[#', $selector) ? '' : '@.';
$exploded = explode('.', $prefix.$selector);
$key = array_pop($exploded);
$keySelector = implode('.', $exploded);

Assert::that($this->search("contains(keys($keySelector), '$key')"))
->equals(true, 'Element with selector "{selector}" not found.', ['selector' => $selector]);

return $this;
}
Expand All @@ -83,15 +85,15 @@ public function assertHas(string $selector): self
*/
public function assertMissing(string $selector): self
{
try {
$this->search("length({$selector})");
} catch (\RuntimeException $e) {
Assert::pass();
$prefix = 1 === preg_match('#^\[#', $selector) ? '' : '@.';
$exploded = explode('.', $prefix.$selector);
$key = array_pop($exploded);
$keySelector = implode('.', $exploded);

return $this;
}
Assert::that($this->search("contains(keys($keySelector), '$key')"))
->equals(false, 'Element with selector "{selector}" exists but it should not.', ['selector' => $selector]);

Assert::fail('Element with selector "{selector}" exists but it should not.', ['selector' => $selector]);
return $this;
}

/**
Expand Down
7 changes: 7 additions & 0 deletions tests/JsonTest.php
Expand Up @@ -71,6 +71,13 @@ public function selectorExistsProvider(): iterable
yield ['{"foo":{"bar": "baz"}}', 'foo.bar'];
yield ['[{"foo":"bar"}]', '[0].foo'];
yield ['{"foo":[{"bar": "baz"}]}', 'foo[0].bar'];
yield ['{"foo": 1}', 'foo'];
yield ['{"foo": ""}', 'foo'];
yield ['{"foo": 0}', 'foo'];
yield ['{"foo": false}', 'foo'];
yield ['{"foo": null}', 'foo'];
yield ['{"foo": {"bar": null}}', 'foo.bar'];
yield ['{"foo": [{"bar": null}]}', 'foo[0].bar'];
}

public function selectorDoesNotExistProvider(): iterable
Expand Down

0 comments on commit f4596c8

Please sign in to comment.