Skip to content

Commit 6d415c7

Browse files
committed
add unit test and query count for index()
1 parent bdd52e8 commit 6d415c7

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

tests/Http/Controllers/PublicWikiControllerTest.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
use App\Wiki;
88
use App\WikiProfile;
99
use Illuminate\Foundation\Testing\DatabaseTransactions;
10+
use Illuminate\Support\Facades\DB;
11+
use Illuminate\Database\Events\QueryExecuted;
1012
use Tests\TestCase;
1113

1214
class PublicWikiControllerTest extends TestCase {
@@ -31,4 +33,35 @@ public function testShowEagerLoadsWikiLatestProfileForResource(): void {
3133
$this->assertInstanceOf(PublicWikiResource::class, $resource);
3234
$this->assertTrue($resource->resource->relationLoaded('wikiLatestProfile'));
3335
}
36+
37+
public function testIndexEagerLoadsWikiLatestProfileOnceForCollection(): void {
38+
$n = rand(3, 100);
39+
echo $n;
40+
for ($i = 1; $i <= $n; $i++) {
41+
$wiki = Wiki::factory()->create([
42+
'domain' => 'index-eager-load-test-' . $i . '.wikibase.cloud',
43+
'sitename' => 'Index Eager Load Test Site ' . $i,
44+
]);
45+
46+
WikiProfile::create([
47+
'wiki_id' => $wiki->id,
48+
'purpose' => 'data_hub',
49+
'temporality' => 'permanent',
50+
'audience' => 'wide',
51+
]);
52+
}
53+
54+
$profileQueryCount = 0;
55+
DB::listen(function (QueryExecuted $query) use (&$profileQueryCount): void {
56+
if (str_contains($query->sql, 'wiki_profiles')) {
57+
$profileQueryCount++;
58+
}
59+
});
60+
61+
$controller = new PublicWikiController;
62+
$resourceCollection = $controller->index(request());
63+
64+
$this->assertSame(1, $profileQueryCount);
65+
$this->assertTrue($resourceCollection->collection[0]->resource->relationLoaded('wikiLatestProfile'));
66+
}
3467
}

0 commit comments

Comments
 (0)