Defining routes

Let's start by defining the first routes we need and how we want them to behave and simple logical steps building what's strictly essential first, in a TDD style.

  1. The first thing is that we need users to be able to register; the smallest test case to register our user is as follows:
    '''javascript
    var dbCleanup = require('./utils/db')
    var expect = require('chai').expect;
    var request = require('supertest'),
    var app = require('../src/app'),
    
    describe('Registration', function() {
      it("shoots a valid request", function(done){
        var user = {
          'email': 'supertest'+Math.random()+'@example.com',
          'name': 'Super'+Math.random(),
        };
    
        request(app)
          .post('/register')
          .send(user)
          .expect(200, done);
      })
    })
  2. Assuming you have Mocha installed with npm i -g mocha, execute mocha.
  3. See 404? Good start! Now let's expand and create a file, src/route/index.js, which will declare all the routes known to the app. It uses controllers that handle each concern.
  4. Start with user.js, which implements a create action, as shown in the following code:
    '''javascript
    // src/routes/index.js
    module.exports = function() {
      var router = require('express').Router();
      var register = require('./user)();
      router.post("/user", user.create);
      return router;
    };
    
    // src/routes/user.js
    module.exports = function() {
      var methods = {};
    
      methods.create = function(req,res,next) {
        res.send({});
      }
    
      return methods;
    };
  5. This amount of code should be enough to make the tests pass with Mocha.
    Defining routes
  6. For this app, we'll have all route definitions in one place, that is, routes/index.js.

At this stage, we know that the testing setup works. Next, let's move onto persistence and some business logic!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.254.90