1

I have the following services that return Bookshelf model data. The server is built on express. My core question is: I want to write tests for the services. Secondarily, I'm not sure if the services tests should include interaction with db; as you can see below, the services are currently intertwined with express.

// services.js

import Region from "../../models/region";
import Subregion from "../../models/subregion";
import bookshelf from "../../bookshelf.config";

/** Regions **/
export const getRegions = (req, res, next) => {
  Region.forge()
    .fetchAll()
    .then(regions => {
      log.info("Got all regions");
      res.status(200).json(regions);
    })
    .catch(next);
};

/** Subegions **/
export const getSubregions = (req, res, next) => {
  Subregion.forge()
    .fetchAll({
      columns: ["id", "name"],
    })
    .then(subregions => {
      res.status(200).json(subregions);
    })
    .catch(next);
};

Questions
1. Whats is the proper way to test a function like getRegions?
2. Do best practices require getRegions and getSubregions to be extracted from the express context?

Kwhitejr
  • 2,206
  • 5
  • 29
  • 49

2 Answers2

1

You have to analyze what your function does and what is the best way to test it. Looking at the getRegions function it just fetches all models of a certain type and returns the result as JSON to the user.

Given this, you have very little logic of your own, it's just a little bit of glue between two modules, so it doesn't make sense to unit test that function because you would just be testing if the used modules (Bookshelf and Express) are working properly, which should be beyond the scope of your project.

However, you probably do want to test if your API is responding correctly with various user inputs, so you should do some integration testing with something like SuperTest.

As for testing with an actual database or mocking it I think that's just a matter of personal opinion or project goals.

devius
  • 2,736
  • 22
  • 26
0
  1. getRegions is just a function. You'd test it like a normal function. You would need to mock the Express' res, req, and next objects. In addition to the Express objects, you would need to mock Bookshelf/knex as well since you don't want to depend on an actual database. See this answer for bookshelf testing.

  2. It is already extracted from Express' context since you defined it as a function. If you had defined it as app.post('/example' (req, res, next) => {}), then that would be coupled with Express.

Cisco
  • 20,972
  • 5
  • 38
  • 60