How to test with toBrowser()? #143
Unanswered
th-alanreed
asked this question in
Q&A
Replies: 1 comment 1 reply
|
When exit; is executed, it terminates the script immediately, preventing PHPUnit from continuing the test execution. Since we cannot remove exit from the package code. Instead of calling toBrowser(), modify your export logic to support both file downloads and file storage when testing. // If running tests, save to a file instead of calling `toBrowser()`
if (app()->runningUnitTests()) {
$path = storage_path('test_export.csv');
$csv->toFile($path);
return response()->json(['message' => 'CSV saved for testing', 'path' => $path]);
}
return $csv->toBrowser('export.csv');in tests public function test_csv_export_creates_valid_csv_file()
{
// Call the export route
$response = $this->get('/export/csv');
// Assert JSON response contains the file path (since we store in tests)
$response->assertJson(['message' => 'CSV saved for testing']);
// Get the file path from response
$csvPath = storage_path('test_export.csv');
// Assert the file exists
$this->assertFileExists($csvPath);
// Read the content and assert it contains expected data
$csvContent = file_get_contents($csvPath);
$this->assertStringContainsString("ID,Name,Email", $csvContent);
$this->assertStringContainsString("John Doe,john@example.com", $csvContent);
// Cleanup: Delete the test file after checking
unlink($csvPath);
}(From ChatGPT) This solution worked for me. |
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
I am using streamDownload() and toBrowser() to download a CSV. I am trying to write a test that verifies a CSV was downloaded and checks the file contents.
However, toBrowser() appears to call exit() which aborts the rest of the request.
simple-excel/src/SimpleExcelWriter.php
Line 230 in 9e7f872
Maybe this is outside of the scope of this package, but is there a way to test a download worked?
All reactions