关于Laravel如何测试CSV下载,当您生成 CSV 时,您如何测试它的运行。采取以下方式:

public function export()
{
    $actions = $this->getData()->get();

    $columns = [
        'User',
        'Start Date',
        'End Date',
    ];

    $data = [];
    foreach ($actions as $action) {
        $data[] = [
            $action->user->name ?? '',
            $action->due_at,
            $action->completed_at,
        ];
    }

    $now      = Carbon::now()->format('d-m-Y');
    $filename = "actions-{$now}";

    return csv_file($columns, $data, $filename);
}

以上收集数据并将其发送到名为 csv_file 的辅助函数,该函数又将导出 CSV 文件。

为了完整起见,它包含:

if (! function_exists('csv_file')) {
    function csv_file($columns, $data, string $filename = 'export'): BinaryFileResponse
    {
        $file      = fopen('php://memory', 'wb');
        $csvHeader = [...$columns];

        fputcsv($file, $csvHeader);

        foreach ($data as $line) {
            fputcsv($file, $line);
        }

        fseek($file, 0);

        $uid = unique_id();

        Storage::disk('local')->put("public/$uid", $file);

        return response()->download(storage_path('app/public/'.$uid), "$filename.csv")->deleteFileAfterSend(true);

    }
}

现在有 2 个测试我想首先确认,我得到 200 状态响应以确保端点不会抛出错误,其次,响应包含为 CSV 生成的文件名。

为了迎合 200 状态代码,运行端点和assertOk()这是 200 而不是assertStatus(200)的快捷方式

接下来检查响应的标头并读取 content-disposition 标头,这将包含一个附件,后跟文件名。 执行断言 true 并将标头与预期响应进行比较;

test('can export actions', function () {
    $this->authenticate();

    $response = $this
        ->get('admin/reports/actions/csv')
        ->assertOk();

    $this->assertTrue($response->headers->get('content-disposition') == 'attachment; filename=actions-'.date('d-m-Y').'.csv');
});

另一种方法是使用 Pest 的 expect API:

$header = $response->headers->get('content-disposition');
$match = 'attachment; filename=actions-'.date('d-m-Y').'.csv';

expect($header)->toBe($match);
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。