I am kind of a test junky and always try to get my apps code coverage close to 100%. It’s not that I like writing tests which I do not think that anybody does, it’s because I’ve had too many bad experiences with code related bugs.
There is nothing more frustrating than having to go back to old code and tweak it because it had bugs or did not work as expected. Not to mention when you tweak the code in one place that seemingly should not affect other parts actually creates more new bugs than what the actual bugfix solved.
In a recent Laravel project, I worked on I used Laravel Dusk to test the app thoroughly. I figured that since it tests your app in the browser with all assets loaded it should be as close to a real-world scenario as possible and should be a solid way of testing your app, right?
However, as much as I like Laravel Dusk I found E2E testing is too heavy to rely on solely. It takes too long time to launch the browser and load all assets and render the page before you can actually start testing your code I have switched to using E2E testing more as something that compliments other types of testing rather than the only and primary way.
I have found that unit testing JS code is really fast and if used with Karma Runner you can target different browsers and actually make the test run inside a real browser, which together with some E2E testing, to me feels like the most efficient way to test your app.
So without further ado, let’s start by creating a new Laravel project.
Then create a config file for Karma Runner with the filename karma.conf.js in the root of your repository
Next, we need to install Karma Runner and other necessary NPM dependencies, like so:
We also need to install Laravel Mix and other Laravel NPM dependencies by running the npm install command:
Next, let’s create a sample test file to see that things are working as expected, add the following contents to a file on this path, resources/assets/js/components/ExampleComponent.spec.js, this will test the ExampleComponent that is shipped with Laravel.
If you have installed Karma globally you can now run karma start to run your tests, if you installed karma locally as proposed in this setup then add a new command to your package.json that looks like this:
Now you can run npm run karma-start to start the Karma Runner and execute your tests, try it out and you should see SUCCESS! written in beautiful green letters.
The full repository is located here: