Skip to main content

Fake in Packages: Laravel Excel Example

Premium
3 min read

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 of our courses? (30 h 33 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.