diff --git a/src/behaviors/TestableResponseBehavior.php b/src/behaviors/TestableResponseBehavior.php index 36db9de..cd25ab7 100644 --- a/src/behaviors/TestableResponseBehavior.php +++ b/src/behaviors/TestableResponseBehavior.php @@ -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 diff --git a/src/test/RequestBuilders.php b/src/test/RequestBuilders.php index 1c7b7c6..40a2283 100644 --- a/src/test/RequestBuilders.php +++ b/src/test/RequestBuilders.php @@ -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. diff --git a/tests/RequestBuilderTest.php b/tests/RequestBuilderTest.php new file mode 100644 index 0000000..1dcdb41 --- /dev/null +++ b/tests/RequestBuilderTest.php @@ -0,0 +1,16 @@ +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'); +}); diff --git a/tests/templates/post-data.twig b/tests/templates/post-data.twig new file mode 100644 index 0000000..f253519 --- /dev/null +++ b/tests/templates/post-data.twig @@ -0,0 +1,4 @@ +{% if craft.app.request.getAcceptsJson() %} + {% header "Content-Type: application/json" %} +{% endif %} +{{ craft.app.request.getBodyParams()|json_encode|raw }}