【问题标题】:Exception when testing CursorPaginator测试 CursorPaginator 时出现异常
【发布时间】:2021-12-30 07:19:12
【问题描述】:

我遇到了一个问题,即以下代码仅在测试中失败,而在浏览器中表现正确。

代码应为 Eloquent 集合提供 CursorPaginator 并将其作为 JSON 返回。

测试代码:

public function testMoreNotesAreReturnedIfRequested()
{
    $item = Item::factory()->has(Entry::factory()->for($this->user)->count(6))->create();

    // Get page one of paginator, and request page 2 using the URL it returns
    $response = $this->actingAs($this->user)->json('get',"/items/{$item->id}/notes/more");
    $next = $this->actingas($this->user)->json('get',$response->decodeResponseJson()['next_page_url']);

    $next->assertJson(fn (AssertableJson $json) => $json
        ->has('data')
        ->has('paginator'));
}

上述失败,但有以下异常:

光标分页项目时仅支持数组和对象。

我已确认在第 1 行中创建了 6 个条目,并且按照谷歌搜索问题时的建议,它们都有不同的毫秒创建时间。

有什么想法吗?

控制器代码:

return $item->entries()
            ->latest()
            ->with(['content','user'])
            ->cursorPaginate(5)
            ->withPath("/items/$item->id/notes/more")
            ->through( static function ($item) use ($request) {
                $item->setAttribute('can_edit',$request->user()->can('update',$item->content));
                $item->setAttribute('can_delete',$request->user()->can('delete',$item->content));
                return $item;
            });

编辑 - 测试每次都失败,而浏览器只有在集合中的项目数为 6、7、16 或 17 时才会失败。我现在更加困惑。

【问题讨论】:

  • 阅读here中的红框,我认为这不是错误,是您没有使用order by...。阅读文档以便您不要浪费时间和精力尝试解决可能会损害您的心理健康的问题。
  • @matiaslauriti 是 'latest()' 而不是 'orderBy("created_at","desc")' 的别名?
  • 是的,但如果我不感到困惑,您应该使用id 而不是created_at。无论哪种方式,您是否尝试手动写入 ->orderBy('created_at', 'desc') 并查看是否有效?

标签: laravel phpunit laravel-8


【解决方案1】:

这似乎是由于使用latest() 进行订购造成的。问题已通过更改为解决

->orderBy('id','desc')

人们遇到的相关问题似乎表明日期戳的精度存在问题(在我的情况下,MariaDB 在第二个之后提供 6 个小数位)。请参阅herehere

我想知道这是否是 CursorPaginator 中的错误。

【讨论】:

    猜你喜欢
    • 2015-11-20
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-13
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多