Reputation: 92687
I have trouble in create tests for my API in laravel. Here how look my routes.php:
Route::group(['middleware' =>'api', 'prefix' => '/api/v1', 'namespace' => 'Api\V1'], function () {
Route::post('/login', 'Auth\AuthController@postLogin');
Route::group(['middleware' =>'jwt.auth'], function () {
Route::post('/projects', 'ProjectsController@postProjects');
...
});
});
My ProjectsController@postProjects
looks like this (I test it by POSTman and it works fine):
public function postProjects() {
$project = new Project;
$project->fill(request()->all());
$project->user_id = Auth::user()->id;
$project->save();
return ['project_id' => $project->id];
}
I write my own middelware for authentication using JWT cookie which is described in details here. But in my test, I try to turn off middelware (use WithoutMiddleware
)and act as logged user (actingAs($user)
- I have user (id=1) in my DB). My test looks like that (I wrote it using this documentation):
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Models\User;
class ProjectsTest extends TestCase
{
use WithoutMiddleware;
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
$user = User::find(1);
$this->actingAs($user)
->json('POST', '/projects', ['name' => 'Project_test_name' ])
->seeJson([
'project_id' => 1,
]); // THIS IS LINE 26
}
}
But I get the following error during execution of vendor/bin/phpunit
:
Time: 182 ms, Memory: 13.75MB
There was 1 error:
1) ProjectsTest::testBasicExample ErrorException: Invalid argument supplied for foreach()
/Users/Kamil/Desktop/Code/kumarajiva.com/vendor/laravel/framework/src/Illuminate/Support/Arr.php:494 /Users/Kamil/Desktop/Code/kumarajiva.com/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:232 /Users/Kamil/Desktop/Code/kumarajiva.com/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:257 /Users/Kamil/Desktop/Code/kumarajiva.com/tests/ProjectsTest.php:26
FAILURES! Tests: 2, Assertions: 2, Errors: 1.
Any ideas what to do with this error?
Upvotes: 1
Views: 1402
Reputation: 380
I encountered the same error. Later I found out the problem: the server wasn't returning JSON, but it returned an "Unauthorized" error. Trying to parse the response as JSON throws the error.
Try to add ->dump() instead of the seeJson() to see what the response is.
Upvotes: 2