Using Grunt to Mock Endpoints Using Grunt to Mock Endpoints angularjs angularjs

Using Grunt to Mock Endpoints


I've fixed this issue by using express to write a server that responds with static json.

First I created a directory in my project called 'api'. Within that directory I have the following files:

package.json:

   {     "name": "mockAPI",     "version": "0.0.0",     "dependencies": {        "express": "~3.3.4"      }   }

Then I run npm install in this directory.

index.js:

    module.exports = require('./lib/server');

lib/server.js:

    express = require('express');    var app = express();    app.get('/my/endpoint', function(req, res){        res.json({'foo': 'myMockJSON'});   });    module.exports = app

and finally in my global Gruntfile.js:

         connect: {            options: {               port: 9000,               hostname: 'localhost',            },            livereload: {              options: {                 middleware: function (connect, options) {                   return [                     lrSnippet,                     mountFolder(connect, '.tmp'),                     mountFolder(connect, yeomanConfig.app),                     require('./api')                   ];               }            }         },

Then the services make the requests, and the express server serves the correct JSON.

After grunt build, the express server is simply replaced by a rails server.


As of grunt-contrib-connect v.0.7.0 you can also just add your custom middleware to the existing middleware stack without having to manually rebuild the existing middleware stack.

livereload: {    options: {        open: true,        base: [            '.tmp',            '<%= config.app %>'        ],        middleware: function(connect, options, middlewares) {            // inject a custom middleware into the array of default middlewares            middlewares.push(function(req, res, next) {                if (req.url !== '/my/endpoint') {                    return next();                }                res.writeHead(200, {'Content-Type': 'application/json' });                res.end("{'foo': 'myMockJSON'}");            });            return middlewares;        }    }},

See https://github.com/gruntjs/grunt-contrib-connect#middleware for the official documentation.


Alternatively you can use the grunt-connect-proxy to proxy everything that is missing in your test server to an actual backend.

It's quite easy to install, just one thing to remember when adding proxy to your livereload connect middleware is to add it last, like this:

middleware: function (connect) {    return [        lrSnippet,        mountFolder(connect, '.tmp'),        mountFolder(connect, yeomanConfig.app),        proxySnippet    ];}