1

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

  • 1
    What sort of logic are you testing in the controllers? – Robert Harvey Jun 20 '18 at 19:53
  • 1
    with unit-testing the more isolation is usually better; the separation of components in MVC, is supposed to allow you to isolate the controller for testing. How you mock and set up your tests is dependent on the actual tests themselves, what they are testing etc. – esoterik Jun 20 '18 at 20:17
  • @RobertHarvey apologies for late reply, but my controllers contains a very limited logic of calling of different sorts of model methods creating/reading/updating/deleting entries in DB and few functions called for data manipulation – Anshul Sahni Jun 22 '18 at 6:52
3

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.

  • Would like to add something to your answer, pushing out all the logic out of the controller seems a bit difficult but I realise that I should only call all sorts of functions from models or helper classes inside the controller and then can unit test all those models and helpers independently so there will be no need to actually unit test the controller instead of some integration testing or end to end testing will automatically implement the double check on the functioning of the controller. So basically controller will only be used for implementing the already unit tested methods. – Anshul Sahni Jun 22 '18 at 6:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.