Mock Server
Guides
Import JS Files

Importing JavaScript files

A simple Mock Server definition will generally start out as a single main.js file, but as more routes and logic is added to the definition your main.js file can grow to an unmaintainable size. To solve this you need to split it up into more maintainable pieces, just like any other JavaScript code you are writing.

Mock Server supports more complex JavaScript file structures through the use of the require() function. The require() function behaves the same as the identically named function in NodeJS, and allows you to execute and import JavaScript from other local files. The only difference between the NodeJS style require and the Mock Server require is that our version only works with files local to your Mock Server (for performance reasons), so no remote URLs.

Below is a simple example of using the require() function in a Mock Server definition:

routes/route1.js:

exports.getHello = function (req, res) {
    res.send("Hello!")
  };

main.js:

var route1 = require('./routes/route1.js')
//routes
mock.define('/hello', route1.getHello)

The above example enables you to define your specific routes in individual files, and keeps your main.js clean. This pattern can also obviously be used in plain JavaScript too, for example to import common utility code into all your routes:

routes/utils.js:

exports.calculateSomething = function (num1, num2) {
    return num1 * num2;
  };

routes/route1.js:

var utils = require('./utils.js');
 
exports.getHello = function (req, res) {
  res.send("Hello!" + utils.calculateSomething(3, 4));
};

main.js:

var route1 = require('./routes/route1.js');
 
//routes
mock.define('/hello', route1.getHello);

Just like in NodeJS require() you need to be aware of the relative path of the file you are requiring. If the file is in the same directory then ./blah.js will work, but ../blah.js is needed if the file is in the parent directory.