How to test your JavaScript components

Testing is not always as easy as we want but is really necessary when we write software but is almost equal necessary to understand which parts have to test and how to structure our code.

The first, and most important error when we write Fronted code is to have everything inside the components, let’s see how I recommend structuring things in the projects.

How some people structure the components

As you can see we have three types of logic:

  • View Logic
Example of logic inside the view layer
  • Component Logic
Example of logic inside the component layer, related to the component
  • Data Logic (Data related to the Business logic of the application/api/backend)
Example of logic inside the component layer, related to the data

The problems of this kind of structure (everything inside the component, to have the component as isolated as possible), are basically two:

  • Your tests always depend on mock the frameworks, and use this kind of mocks is not always sweeeeet 👀
  • My experience checking and auditing code from some different types of teams and projects, teach me that isolating this so much, sometimes, make that ui or e2e tests are too much similar to unit tests.

Ok, but now what? We can separate the code in another way.

How we like to divide our components
  • View Logic

Easy, NEVER put logic into your view 😇

Example of view layer without logic

If you have logic into your view, move it to your component.

Example of the view logic, moved to the component
  • Component Logic

If the logic is related to the view, keep it into the component, but if not (related to data layer) move it to a service.

Example of the component logic moved to a service because is data logic

or, if the method is too basic…

Example of the view communicating, directly to the service
  • Data Logic

Never in the component, always in services/utils/helpers/stores/etc… OUTSIDE the component logic.

And what happened now? Just compare.

The big percentage of the unit tests will be in our services/utils/helpers/stores… this means that will be very easy to test it without mocking a framework.

You can (if you need) do some small tests into your components, but probably will be enough with some unit tests in data logic and e2e tests for services + components.

And you? How you test? Yes, Tests are always crazy, but here you have a small workshop about Testing Vue Project with Karma + Mocha + Chai + Sinon.