Pregunta

I'm writing a REST api backend in NODE js, which is based on MVC approach. My api routes directly hit the controllers, which in turn import models which are a wrapper around the methods from a library (DB ORM) called sequelize.

What will be the better approach for writing the unit tests for the controllers,

  1. To include models, with mock DB data, in unit tests of the respective controllers
  2. To somehow mock the models and then unit test my controllers without involving the real models at all.

If the second approach is better how will I achieve writing these types of Unit tests

¿Fue útil?

Solución

The usual wisdom for MVC architectures is this:

  1. Push as much logic away from the View as possible.
  2. Push as much logic out of the Controller into the Model as possible.

In practice, this makes for fat models, thin controllers and UI that is merely a surface area for the user to interact with.

What this means from a testing perspective is that there really shouldn't be much logic in the controller to test. The controller should be acting mostly as a "switch-yard." For the most part, integration tests will tell you whether your controllers are functioning normally.

That means that the vast majority of your unit tests will be focused on the Model, where you will be dealing mostly with plain ol' classes.

Licenciado bajo: CC-BY-SA con atribución
scroll top