Search code examples
node.jsexpressmocha.jssupertest

How do I import routes for testing with Supertest?


I have an application tested by Mocha and I'm able to successfully run my tests with what I have now, but I'm explicitly setting a GET route to /api/v1 within my test file. Here's the test file...

API.js:

var request = require('supertest');
var express = require('express');
var app = express();
var router = express.Router();

app.get('/api/v1', function (req, res, next) {
  res.json({
    "Hello": "World"
  });
});

describe('API', function () {
  it("Says 'Hello' is 'World'", function (done) {
    request(app)
      .get('/api/v1')
      .expect('Content-Type', /json/)
      .expect(200, {
        Hello: 'World'
      }, done);
  });
});

Have you noticed how I say app.get() after the require() statements? I don't want to do that here. I want to be able to import my routes from the routes directory of my project.

I find it hard to believe that I'm supposed to duplicate all of these routes in my test file. How would I want to import the routes from the routes directory for use in this testing file?


Solution

  • It is not required that the routes be imported into the test file. Once routes have been defined on the express.Router object, and the app uses the router, the app need only be exported from the main application file.

    You'll define your routes in a separate file and export the router. routes.js

    var express = require('express');
    var router = express.Router();
    
    // Define routes
    router.get('/api/v1', function (req, res, next) {
      res.json({
        "Hello": "World"
      });
    });
    
    // Export the router. This will be used in the 'app.js' file.
    

    app.js

    //Import the router
    var router = require('./routes');
    
    // Use the router as middleware for the app. This enables the app to
    // respond to requests defined by the router.
    app.use('/', router);
    
    // Export the app object
    module.exports = app;
    

    app.spec.js

    // Import the app
    var app = require('./app');
    
    // Use the app object in your tests
    describe('API', function () {
      it("Says 'Hello' is 'World'", function (done) {
        request(app)
          .get('/api/v1')
          .expect('Content-Type', /json/)
          .expect(200, {
            Hello: 'World'
          }, done);
      });
    });
    

    express.Router helps organize your routes. The question is answered perfectly here: What is the difference between "express.Router" and routing using "app.get"?