1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Laravel]assertExactJsonが勝手にsortしちゃう...

Last updated at Posted at 2022-03-26

TL;DR

  • コレクション渡したときに自動でキーを昇順でsortするため、実際にAPIで用意した順番通りにならない
  • 配列値に渡したときにassertExactJson使った際の取得値が配列に置き換えられている

Controllers

    return response()->json([
        'success' => true,
        'orders' => $orders->map(function ($order) {
            return [
                'uuid' => $order->uuid,
                'name' => $order->name,
                'phone_number' => $order->phone_number,
                'updated_at' => $order->updated_at->format('Y-m-d H:i:s.u'),
            ];
        }),
    ]);

uuid, name, ...の順が想定値

ControllerTest.php

$response = $this->actingAs($user)->getJson(route('api.orders.index'));

$response->assertExactJson([
    'success' => true,
    'orders' => $orders->map(function ($order) {
        return [
            'uuid' => $order->uuid,
            'name' => $order->name,
            'phone_number' => $order->phone_number,
            'updated_at' => $order->updated_at->format('Y-m-d H:i:s.u'),
        ];
    });
]);

テスト結果

--- Expected
+++ Actual
@@ @@
// APIで渡している内容
-'{"success":true,"orders":[{"uuid":"a6ba578e-8a5c-4a50-8f49-ba21bb53c6d2","name":"\u8061\u592a\u90ce","phone_number":"\u8061\u592a\u90ce",updated_at":"2022-03-11 10:36:07.416040"}]}'
// 勝手にABC順でソートされている
+'{"success":true,"orders":[{"name":"\u8061\u592a\u90ce","phone_number":"\u8061\u592a\u90ce", updated_at":"2022-03-11 10:36:07.416040","uuid":"a6ba578e-8a5c-4a50-8f49-ba21bb53c6d2"}]}'

テストでget送信して取得した内容がbuildingから始まっている

 →勝手にソートしている

対策

テスト時に配列を渡すようにする

$response->assertExactJson([
    'success' => true,
    'orders' => $orders->map(function ($order) {
        return [
            'uuid' => $order->uuid,
            'name' => $order->name,
            'phone_number' => $order->phone_number,
            'updated_at' => $order->updated_at->format('Y-m-d H:i:s.u'),
        ];
    });
		->toArray();
]);

これもassertExactJsonの仕様だが、配列を渡すと想定値も配列に変換され、コレクションの様にソートされないので、配列を使う

テスト結果

しっかりテスト通る

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?