mvieira's avatar

Laravel Testing with Return compact()

I have this legacy method that it needs to be tested.

It returns a compact();

 return compact('forms'); 

In my testcase I am trying to catch this return without success.

$response = Http::post($url, [
    'name' => 'xxx',
    'role' => 'xxxx',
]);

The response is returning Null.

  • When I change the return in the method to (below) than it works *
return response()->json([
            'data' => $forms,
        ]);

Does anyone have an idea how?

0 likes
3 replies
automica's avatar

usually you would pass your data into a view with compact or return a response if you want json back.

I can't see why compact wouldn't work in your test though as its standard php method https://www.php.net/manual/en/function.compact.php

can you show the whole method you are testing, along with the version of laravel?

1 like
mvieira's avatar

If I am correct the original version of the laravel project was 5 ( It could be lower but I am not sure ) and it was updated to 7.2.

I had fixed the problems with the testing files ( testcase.php , composer.json, ... ) and now it works, but I notice this problem.

Regarding the method it is quite long, but it is working fine and it is also an endpoint - ( tested on Postman ).

I know that there are major changes in the front-end but I am working more on the back. Compact() is being used instead of response()->json() , which I tested and it worked in my tests.

And from the testing part, here is a simple test the confirms a member_id ( it only works if I changed to a json return in the method.

public function testExample()
    {
        $json_post_array = [
            "forms" => [
                  [
                     "sex" => "1", 
                     "user_id" => 342868, 
                     "security_id" => 297345,
					...
					] 
               ] ];
$response = Http::post($url, [$json_post_array]); 
$response = json_decode($response);
$this->assertEquals($response->data[0]->member_id,99463);
  • I have removed some stuff so it would be simple to read.
mvieira's avatar

Solved. There were other things in the code that were throwing some type of error that only happenned with a certain type of data.

2 likes

Please or to participate in this conversation.