Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

Testing a Vue component part 5: Jest awesomeness and a skeleton to get started

Welcome to part 5 of a series on how to test a Vue component.

Here’s the table of contents of the series:

  1. Starting out with tests
  2. The first test and snapshot testing
  3. Creating an instance of a component
  4. More tests and faking time
  5. Jest awesomeness and a skeleton to get started (you’re here)

Jest watch mode

You know by now that Jest is an amazing testing tools that comes with jsdom and snapshot testing built in. But a thing we haven’t touched upon is it’s test runner. Typing jest on the command line will make it run all the tests but it can do much more. It has an awesome interactive mode that you can start by jest --watch.

When Jest is in this mode it will run the tests when one of the files in your project changes. You can also press enter to manually trigger a test run. A very cool feature is that you can put a filter on which tests to run by pressing t (or p).

Now when a file changes only the tests containing storage in their name will run. I really wish all test runners (I’m looking at you PHPUnit) had this built in.

Our skeleton repository

Like already mentioned getting started with testing a Vue component was a pain because you need to have a good environment set up. To avoid going to through the same pain again I created a skeleton repo to kickstart Vue component development. Sebastian played a big role is setting all this up just right. This repo is what I’ll be using myself when working on the next component.

Here’s how you can get started with it:

  1. Clone the repo [email protected]:spatie/skeleton-vue.git
  2. Run rm -rf .git && git init to cut loose the connection to our repo on GitHub
  3. Run yarn to pull in the dependencies.
  4. Replace all occurrences of the string mentioned at the top of the readme.

The skeleton already contains an ExampleComponent and a test to make sure that component is working. If you run ./node_modules/.bin/jest you’ll see that test is passing.

In closing

Congratulations, you’ve reached the end of this series. I hope you liked learning all this stuff and that reading all of this make you want to start creating and testing a Vue component of your own. Although starting with testing may be daunting, try to persist and eventually you will be rewarded with progress and results. If you feel like you’re stuck ask a colleague or a programming friend for some help.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band. He loves waffles and butterflies.