HTTP Assertions for PEST (Without Laravel)? #1309
Replies: 1 comment
-
Hey! 👋 If you're looking for HTTP assertion tools for PEST without relying on Laravel, you’ve got a few lightweight options that can work well: 1. pestphp/pest-plugin-httpThis is a lightweight HTTP plugin for PEST that doesn’t depend on Laravel, designed specifically for making HTTP assertions easy. It’s not an official plugin, but you can install it from the community resources on GitHub. It’s a simple wrapper around Guzzle, allowing you to use assertions similar to Laravel’s HTTP assertions. To install, you can try: composer require pestphp/pest-plugin-http Then, in your tests, you could do something like: it('makes a successful GET request', function () {
$response = http()->get('https://api.example.com/endpoint');
expect($response->status())->toBe(200);
expect($response->json('key'))->toBe('value');
}); 2. Symfony HTTP Client with PESTIf the above isn’t available, Symfony’s HTTP Client is another great alternative. It’s lightweight and doesn’t require Laravel. Install Symfony’s HTTP Client: composer require symfony/http-client Then, you can write assertions like this in PEST: use Symfony\Component\HttpClient\HttpClient;
it('returns a successful response', function () {
$client = HttpClient::create();
$response = $client->request('GET', 'https://api.example.com/endpoint');
expect($response->getStatusCode())->toBe(200);
expect($response->toArray())->toHaveKey('key');
}); 3. Custom Utility FunctionsSince you’re already using Guzzle, you could create some custom helper functions to simplify assertions. For example: function assertHttpStatus($response, int $expectedStatus) {
expect($response->getStatusCode())->toBe($expectedStatus);
}
function assertJsonContains($response, string $key, $value) {
$data = json_decode($response->getBody(), true);
expect($data[$key] ?? null)->toBe($value);
} Then, you can use these functions in your tests: it('makes a successful request', function () {
$response = http()->get('https://api.example.com/endpoint');
assertHttpStatus($response, 200);
assertJsonContains($response, 'key', 'value');
}); These approaches should keep your dependencies lightweight and allow for clean HTTP assertions in PEST. Let me know if this helps or if you have any questions! 😊 |
Beta Was this translation helpful? Give feedback.
-
Hey, everyone!
Does anyone know of a library or plugin that makes it easy to assert HTTP requests in PEST, without requiring Laravel?
I’m aware of the
pestphp/pest-plugin-laravel
plugin, which has HTTP assertion features, but I couldn't get it working (probably a skill issue on my part). Plus, I'm not using Laravel, so pulling in the entire framework and its dependencies is overkill for my needs.I’ve defaulted to using Guzzle with some utility functions, but I’m hoping there’s a more streamlined solution out there.
Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions