Inigo
Inigo

Reputation: 8685

Laravel: Is it possible to directly test the json response output of a function without actually going through the URI?

From the docs, I can test some json returned from my app using the following:

$response = $this->json('POST', '/user', ['name' => 'Sally']);

$response
    ->assertStatus(201)
    ->assertJson([
        'created' => true,
    ]);

However, is it possible to bypass actually calling up the URI with $this->json(*method*, *uri*, *data*); and instead test the direct output of a controller function which returns json? For example, I want to do something like this:

// My controller:

function getPageData(){
  $data = array('array', 'of', 'data');
  return response()->json($data);
}

// My Test Class:

$controller = new Primary();
$response = $controller->getPageData();

$response->assertJson([
    'array', 'of', 'data'
]);

Is this possible?

Upvotes: 0

Views: 1611

Answers (1)

DevK
DevK

Reputation: 9942

You could do this for some basic methods, but it might cause side effects:

app(SomeController::class)->someControllerMethod();

Basically, the app() will resolve the dependencies from the constructor, but it won't resolve the method dependencies. So if you typehint something like method(Request $request), it will throw an error.

I'm pretty sure dealing with request() will cause unintentional effects since there's no real request going on.

Edit:

You could then create a TestResponse object, to get all the asserts as well:

$res = app(SomeController::class)->someControllerMethod();
$testRes = new Illuminate\Foundation\Testing\TestResponse($res);
$testRes->assertJson(...); // Will be available

Upvotes: 2

Related Questions