Skip to content

Commit

Permalink
bit more json support
Browse files Browse the repository at this point in the history
  • Loading branch information
markhuot committed Nov 18, 2023
1 parent 3517eeb commit a8a2425
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/behaviors/TestableResponseBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,11 @@ function getJsonContent()
return json_decode($this->response->content, true);
}

function json()
{
return $this->getJsonContent();
}

/**
* If the response returns HTML you can `querySelector()` to inspect the
* HTML for specific content. The `querySelector()` method takes a
Expand Down
20 changes: 20 additions & 0 deletions src/test/RequestBuilders.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,26 @@ function post(string $uri, array $body=[]): TestableResponse
->send();
}

/**
* Similar to `->post()`, while adding aJSON `content-type` and `accept` headers.
*
* ```php
* $this->postJson('/comments', [
* 'author' => '...',
* 'body' => '...',
* ])->assertOk();
* ```
*/
function postJson(string $uri, array $body=[]): TestableResponse
{
return $this->http('post', $uri)
->withCsrfToken()
->setBody($body)
->addHeader('Content-Type', 'application/json')
->addHeader('Accept', 'application/json')
->send();
}

/**
* Maes a `POST` request to Craft with the `action` param filled in to the
* passed value.
Expand Down
16 changes: 16 additions & 0 deletions tests/RequestBuilderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

it('posts to an action', function () {
$this->post('/post-data', ['foo' => 'bar'])
->assertHeader('content-type', 'text/html; charset=UTF-8')
->assertSee('"foo":"bar"')
->assertOk();
});

it('posts json to an action', function () {
$response = $this->postJson('/post-data', ['foo' => 'bar'])
->assertHeader('content-type', 'application/json')
->assertOk();

expect($response->json())->foo->toBe('bar');
});
4 changes: 4 additions & 0 deletions tests/templates/post-data.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{% if craft.app.request.getAcceptsJson() %}
{% header "Content-Type: application/json" %}
{% endif %}
{{ craft.app.request.getBodyParams()|json_encode|raw }}

0 comments on commit a8a2425

Please sign in to comment.