Back to Course |
Testing in Laravel 11 For Beginners

Should We Test Code From Packages?

Another sub-question to cover on the topic of "what to test": should we test something that is covered by external Laravel/PHP packages?

For example, you use a Spatie package laravel-tags to have tags in your Eloquent models. Should you write a test that the tag is inserted successfully if you do that by calling the function from that package?

That is a debatable question, but most serious package creators include tests in their packages, so package users would not need to test that or retest it manually externally.

So, for example, if we go to test folder of that package, there are quite a lot of tests asserting that if you add a tag, for example, it can create a tag, assert count, assert same, etc. So, a lot of internal unit parts are covered by the package.

So, instead of testing the package behavior, you should test how your application is acting after using the code from the package. For example, in your Controller, you add a tag and then test that the Controller redirects where it needs to redirect.

And that is another thing: you should use the packages that have (enough) internal tests. It proves that the author is serious about the tool they provide. For example, you can look at how many tests are in the Laravel framework itself.

If you think about it, Laravel framework is a package: we install it into our PHP system via composer. So, the same question: should we test something like the internal models of Laravel? Should we test that some Eloquent Model is successfully created? Probably not, because the framework itself has, again, a massive amount of tests.

The analogy could be about building a bridge or a house. For example, a LEGO house. Those units, the bricks, are those Eloquent features or Models that are covered by tests in the (LEGO factory) framework itself. So, the LEGO factory provides the bricks for you. They are tested from their side. And your application is a thing that you're building with LEGO. So, you need a Feature test to ensure your house is stable. You shouldn't focus on testing the bricks.

Important note: if you make your brick structure that would be reusable by others, it becomes a unit to be tested. For example, you build a unique window from LEGO, which would be in various parts of the house. So, you need to have a Unit test, ensuring the window is stable and safe to use in other parts of the house.

But, generally, that's why Laravel docs emphasize that Feature tests should be the majority of what you write. The packages are often mostly covered by tests if serious package creators release them, and you shouldn't cover that twice.