如何测试Laravel资源

问题描述 投票:0回答:1

我正在通过分页测试API端点返回的Laravel资源

 public function test_showing_all_plans(): void
 {
    $plans = Plan::where('is_active', true)
        ->paginate(10);

    $resource = PlansResource::collection($plans);

    $this->withHeaders([
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
        'AppKey' => 5,
    ])
        ->json('GET', '/api/customer/plans')
        ->assertStatus(200)
        ->assertExactJson([
            $resource->response()->getData(true),
        ]);
}

所以我的问题是,由于端点的路径不等于资源的返回,因此返回的结果不相同。

这是从端点返回的结果:

"links": {
        "first": "http://www.site.local/api/customer/plans?page=1",
        "last": "http://www.site.local/api/customer/plans?page=3",
        "next": "http://www.site.local/api/customer/plans?page=2",
        "prev": null
    },
    "meta": {
        "current_page": 1,
        "from": 1,
        "last_page": 3,
        "path": "http://www.site.local/api/customer/plans",
        "per_page": 10,
        "to": 10,
        "total": 24
    }

这是从资源'$resource->response()->getData(true)'返回的代码>]

 "links": {
            "first": "http://www.site.local?page=1",
            "last": "http://www.site.local?page=3",
            "next": "http://www.site.local?page=2",
            "prev": null
        },
        "meta": {
            "current_page": 1,
            "from": 1,
            "last_page": 3,
            "path": "http://www.site.local",
            "per_page": 10,
            "to": 10,
          }

所以我如何将端点传递给我的代码,或者如何使它们相等,并且有测试LaRavel资源的正确方法?

我正在使用分页公共功能test_showing_all_plans()测试API端点返回的Laravel资源:void {$ plans = Plan :: where('is_active',true)-> paginate(10); $ ...

laravel api unit-testing tdd laravel-resource
1个回答
0
投票

The answer lies in the JsonResource::response() method —此方法接受可选的JsonResource::response()参数,该参数将提供有关您尝试使用资源的位置的上下文。

© www.soinside.com 2019 - 2024. All rights reserved.