0

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?

IIllIIll
  • 504
  • 8
  • 25

1 Answers1

4

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"?

Community
  • 1
  • 1
gnerkus
  • 11,357
  • 6
  • 47
  • 71
  • My routes (in the `routes` directory) are attached to `express.Router()`, so what's the difference between `app.get()` and `express.Router()`, and how could I get those routes out of `express.Router()`? – IIllIIll Jan 22 '16 at 21:43
  • Thanks for the clarification. I'll update the answer. – gnerkus Jan 22 '16 at 21:50
  • 2
    Basically I was using `var app = express()` instead of `var app = require('../app')`. Thank you for this! – IIllIIll Jan 23 '16 at 12:31
  • Importing my v1 router causes the `You are trying to import` error – Kewyn Vieira Jul 28 '22 at 16:56