Core\Test\SentRequest::body
$sentRequest->body(): bytesbody() returns the body of one request that your program sent in a test. You get the request from Core\Test::sentHttp(), after Core\Test::answerHttp has set up a fake web service.
The result is bytes, exactly as the program sent them. For a json option it is the encoded JSON document. For a form option it is the encoded form text. If the request has no body, as with most GET requests, the result is empty bytes. Write as string to read the body as text, or pass that text to Core\Json::decode to check each field.
The examples below show how to read a JSON body, a form body and an empty body, and a test that checks the document a shop sends to its payment service.
Return value
Returns bytes. The body as bytes. If the request has no body, the result is empty bytes. Use as string to read it as text.
Examples
Read a json body
<?nvs// Shows how to read the body of a request your program sent.
use Core\Http\Client;use Core\Test;
Test::answerHttp('https://api.example.com/notes', 201);Client::post('https://api.example.com/notes', { json: ['title' => 'Shopping', 'done' => false] });
// `body()` returns `bytes`. `as string` reads the bytes as text.// This prints `{"title":"Shopping","done":false}`.echo Test::sentHttp()[0]->body() as string, "\n";{"title":"Shopping","done":false}A form and a request without a body
<?nvs// Shows the body of a form request and of a request that has no body.
use Core\Http\Client;use Core\Test;
Test::answerHttp('https://api.example.com/*', 200);Client::post('https://api.example.com/login', { form: ['user' => 'ada', 'note' => 'a b'] });Client::get('https://api.example.com/home');
// A form body is encoded text. This prints `user=ada¬e=a+b`.echo Test::sentHttp()[0]->body() as string, "\n";
// A GET request has no body, so the result is empty. This prints `0`.echo Core\Bytes::length(Test::sentHttp()[1]->body()), "\n";user=ada¬e=a+b0Test the order a shop sends
<?nvs// Shows how to test the JSON document a shop sends to its payment service.
use Core\Http\Client;use Core\Test;
class Checkout{ // Asks the payment service to charge an amount in cents. public static function charge(string $orderId, uint $cents): int { return Client::post('https://pay.example.com/charges', { json: ['order' => $orderId, 'amount' => $cents, 'currency' => 'EUR'], })->status(); }}
Test::answerHttp('https://pay.example.com/charges', 201);Checkout::charge('A-17', 2599);
// The test decodes the body and checks each field.// A wrong amount here would charge the customer the wrong price.var $sent = Core\Json::decode(Test::sentHttp()[0]->body() as string);Test::assertSame($sent['order'], 'A-17');Test::assertSame($sent['amount'], 2599);Test::assertSame($sent['currency'], 'EUR');
// This prints `the charge is correct`.echo "the charge is correct\n";the charge is correct