Courses

Testing in Laravel 11: Advanced Level

Fake in Packages: Laravel Excel Example

Summary of this lesson:
- Test third-party package methods
- Use package-specific faking techniques
- Simulate package functionality
- Test Excel import/export scenarios
- Verify package integration

After repeating many examples with Laravel Facades and their fake() method in this course chapter, I will show you one more thing. Some Laravel/PHP packages have their own implementation of faking.


Package Example

For example, a popular package Laravel Excel can be faked in the test. An example from the docs for testing Excel exporting:

/**
* @test
*/
public function user_can_download_invoices_export()
{
Excel::fake(); // [tl ~~]
 
$this->actingAs($this->givenUser())
->get('/invoices/download/xlsx');
 
Excel::assertDownloaded('filename.xlsx', function(InvoicesExport $export) {
// Assert that the correct export is downloaded.
return $export->collection()->contains('#2018-01');
});
}

An example from the docs for testing Excel importing:

/**
* @test
*/
public function user_can_import_users()
{
Excel::fake();
 
$this->actingAs($this->givenUser())
->get('/users/import/xlsx');
 
Excel::assertImported('filename.xlsx', 'diskName');
 
Excel::assertImported('filename.xlsx', 'diskName', function(UsersImport $import) {
return true;
});
 
// When passing the callback as 2nd param, the disk will be the default disk.
Excel::assertImported('filename.xlsx', function(UsersImport $import) {
return true;
});
}

There are more assertions for exporting and importing. Check the documentation.


Open-Source Example

Let's examine a real-world example from an open-source akaunting/akaunting project.

There are...

The full lesson is only for Premium Members.
Want to access all 31 lessons of this course? (74 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord