How to test your Javascript code in Laravel with Jest

Wébert Charles
2 min readFeb 23, 2020

--

Click here for French version

Recently, my company chose to focus a bit more on Javascript to create more dynamic interfaces for users. We’ve chosen to develop more components in VueJs.

But when it comes to test our functions, classes and components, we were a little confused. Finally, we chose to go with Jest. And it works perfectly.

In this article, I’ll show you how to use Jest Test Runner to test your code in a Laravel context.

First thing first, environment

Since your app is already working, you need to do some work in your configuration file to use Jest. But it’s easy to set up.

  1. Install VueJs and vue-template-compiler

2. Install Babel

Create a .babelrc file at the root of your project with those lines of code

.babelrc

3. Install Jest and Jest tools

In of your package.json file make sure to create a test key with the jest value inside of the scripts section. Don’t forget to create a Jest section also.

Test your code

Navigate to resources/js.

Here is the files structure that we will use.

In this section, we are going to test a class and a Vue Component

Test our class “Person”

myClass.js
myClass.test.js

Test our component “myFirstComponent”

myFirstComponent.vue
myFristComponent.test.js

Bug tracker

Requires Babel “7.0.0–0”, but was loaded with “6.26.3”. If you are sure you have a compatible version of @babel/core, it is likely that something in your build process is loading the wrong version.
Inspect the stack trace of this error to look for the first entry that doesn’t mention “@babel/core” or “babel-core” to see what is calling Babel.

If you have this message while testing your components, update your babel-core to 7.0.0-bridge.0.

Final thoughts

If you want to test you code each time you run npm run dev command, you can replace development key in package.js file by the line below.

package.json

If you want to dive into Jest, you can read the documentation by following this link : https://jestjs.io/docs/en/getting-started

--

--