Why does Laravel Livewire test with PHPUnit return a NotFoundHttpException when API returns all User records?

huangapple go评论53阅读模式
英文:

Why does Laravel Livewire test with PHPUnit return a NotFoundHttpException when API returns all User records?

问题

我遇到了在我的API上运行测试时的问题,该API返回用户模型中的所有记录。这很简单。目标是从该模型中检索所有数据。在浏览器中以任何模式和在Postman中都可以正常工作。它始终返回JSON数据。完美。就是这样。

我使用Livewire创建了测试和控制器,我正在使用Laravel、Livewire等的最新版本。
我将与您分享完美运行的控制器代码以及测试代码、我的路由文件等。
首先,这是我的测试中出现的错误消息。

我已经更改了路由的顺序,将路由放在routes/web.php文件中。我已清除了config:clearcache等。我已使用了命名路由,我已取消了命名路由。
我已在Postman和任何浏览器中进行了测试。它有效。
这不是单元测试。这是一个功能测试。
它应该返回状态码200,测试不应该因404错误而失败。

请帮助。

我的控制器文件:app/Http/Livewire/Api/ApiBuzCard.php

<?php

namespace App\Http\Livewire\Api;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use Laravel\Jetstream\Features;
use Illuminate\Http\Request;
use Livewire\Component;

class ApiBuzCard extends Component
{
    public function getAllUsers()
    {
      $users = User::orderByDesc('id')->get()->toJson(JSON_PRETTY_PRINT);

      return response($users, 200);
    }

我的路由文件:routes/api.php

<?php

use App\Http\Livewire\Api\ApiBuzCard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('users', [ApiBuzCard::class, 'getAllUsers'])->name('api.users');

Route::middleware('auth:sanctum')
    ->get('/user', function (Request $request) {
        return $request->user();
    });

Route::get('user/{id}', [ApiBuzCard::class, 'getUser']);

Route::post('users', [ApiBuzCard::class, 'createUser'])
    ->middleware('api');
Route::put('user/{id}', [ApiBuzCard::class, 'updateUser'])
    ->middleware('api');
Route::delete('user/{id}', [ApiBuzCard::class, 'deleteUser'])
    ->middleware('api');

我的测试文件:tests/Feature/ApiBuzCardTest.php

<?php

namespace Tests\Feature\Livewire\Api;

use App\Http\Livewire\Api\ApiBuzCard;
use App\Models\User;
use Livewire\Livewire;
use Tests\TestCase;

class ApiBuzCardTest extends TestCase
{
    /** @test */
    public function the_api_return_all_users()
    {
        $this->withoutExceptionHandling();

        $user = User::factory()->create();

        $response = $this->get('/api/users');
        $response->assertStatus(200);
    }
}
英文:

I'm having trouble running a test on my API that returns all records from the user model. It's simple. The goal is to retrieve all data from this model. It is working fine both in the browser, in any mode, and in Postman. It always returns the data as JSON. Perfect. That's it.
I created both the tests and controllers with Livewire. I'm using the latest version of Laravel, Livewire, etc.
I'll share with you guys, the code of the controller that works perfectly, as well as the test code, my routes file, etc.
First, here's the error message that appears in my test.

I have already changed the order of routes, I have placed the route in the routes/web.php file. I have cleared the config:clear, cache, etc. I have used the named route, I have undone the named route.
I have tested it in Postman and in any browser. It works.
It is not a Unit test. It is a Feature Test.
It should return the status 200, and the test should not fail with the 404 error.

Please Help.

user@server:/var/www/virtual-card$ sudo php artisan test --filter ApiBuzCardTest::the_api_return_all_users

FAIL  Tests\Feature\Livewire\Api\ApiBuzCardTest
⨯ the api return all users                                                                                                                                                                                                                                  0.08s  
─────────────────────────────────────────────
FAILED  Tests\Feature\Livewire\Api\ApiBuzCardTest &gt; the api return all users                                                                                                                                                              NotFoundHttpException  
GET https://server/virtual-card/api/users

at vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:51
47▕         $handler = $this-&gt;container-&gt;make(ExceptionHandler::class);
48▕
49▕         $handler-&gt;report($e);
50▕
➜  51▕         $response = $handler-&gt;render($passable, $e);
52▕
53▕         if (is_object($response) &amp;&amp; method_exists($response, &#39;withException&#39;)) {
54▕             $response-&gt;withException($e);
55▕         }

      +42 vendor frames 

43  tests/Feature/Livewire/Api/ApiBuzCardTest.php:17

Tests:    1 failed (0 assertions)
Duration: 0.12s

My Controller File: app/Http/Livewire/Api/ApiBuzCard.php

&lt;?php

namespace App\Http\Livewire\Api;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use Laravel\Jetstream\Features;
use Illuminate\Http\Request;
use Livewire\Component;

class ApiBuzCard extends Component
{
    public function getAllUsers()
    {
      $users = User::orderByDesc(&#39;id&#39;)-&gt;get()-&gt;toJson(JSON_PRETTY_PRINT);

      return response($users, 200);
    }

My Route File: routes/api.php

&lt;?php

use App\Http\Livewire\Api\ApiBuzCard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get(&#39;users&#39;, [ApiBuzCard::class, &#39;getAllUsers&#39;])-&gt;name(&#39;api.users&#39;);

Route::middleware(&#39;auth:sanctum&#39;)
    -&gt;get(&#39;/user&#39;, function (Request $request) {
        return $request-&gt;user();
    });

Route::get(&#39;user/{id}&#39;, [ApiBuzCard::class, &#39;getUser&#39;]);

Route::post(&#39;users&#39;, [ApiBuzCard::class, &#39;createUser&#39;])
    -&gt;middleware(&#39;api&#39;);
Route::put(&#39;user/{id}&#39;, [ApiBuzCard::class, &#39;updateUser&#39;])
    -&gt;middleware(&#39;api&#39;);
Route::delete(&#39;user/{id}&#39;, [ApiBuzCard::class, &#39;deleteUser&#39;])
    -&gt;middleware(&#39;api&#39;);

My Test File tests/Feature/ApiBuzCardTest.php

&lt;?php

namespace Tests\Feature\Livewire\Api;

use App\Http\Livewire\Api\ApiBuzCard;
use App\Models\User;
use Livewire\Livewire;
use Tests\TestCase;

class ApiBuzCardTest extends TestCase
{
    /** @test */
    public function the_api_return_all_users()
    {
        $this-&gt;withoutExceptionHandling();

        $user = User::factory()-&gt;create();

        $response = $this-&gt;get(&#39;/api/users&#39;);
        $response-&gt;assertStatus(200);
    }

答案1

得分: -1

我在下面的链接上找到了解决方案。用户Sergiu17建议问题出在我的phpunit.xml文件中的以下配置:

<server name="APP_URL" value="http://devlab03.mshome.net/virtual-card"/>

需要更改为 <env name="APP_URL" value="https://localhost"/>
尽管我在官方文档中找不到相关内容,但我认为Laravel测试环境只能在localhost上使用这个配置。
谢谢。

链接:https://laracasts.com/discuss/channels/code-review/laravel-feature-tests-always-return-404

英文:

I found the solution on the link below. The User Sergiu17 suggested that the problem was the following configuration in my phpunit.xml file:

&lt;server name=&quot;APP_URL&quot; value=&quot;http://devlab03.mshome.net/virtual-card&quot;/&gt;

It needs to be changed to &lt;env name=&quot;APP_URL&quot; value=&quot;https://localhost&quot;/&gt;
Although I couldn't find anything in the official documentation, I believe that the Laravel testing environment can only work with this configuration on localhost.
Thank you.

https://laracasts.com/discuss/channels/code-review/laravel-feature-tests-always-return-404

huangapple
  • 本文由 发表于 2023年5月30日 03:05:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76359827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定