Skip to content
This repository has been archived by the owner on May 15, 2019. It is now read-only.

Mocking function dependencies

Jason Dobry edited this page Feb 1, 2017 · 1 revision

When running functions locally you sometimes want to change the behavior of modules which connect to external services. For example you might be accessing a database, API or external system that you don't want to, or can't access from your local environment.

The Cloud Functions Emulator provides a way to inject mock versions of Node.js modules imported into your function.

  1. Enable the use of mocks:

     functions config set useMocks true
     functions restart
    
  2. Edit mocks.js and mock the dependencies you want

     // You can create handcrafted mocks, or use a mocking library
     var sinon = require('sinon');
    
     /**
      * Called when the require() method is called
      * @param {String} func The name of the current function being invoked
      * @param {String} module The name of the module being required
      */
     exports.onRequire = function (func, module) {
         // Return an object or module to override the named module argument
         if (module === 'redis') {
             // Create a mock of redis
             var mockRedis = sinon.mock(require('redis'));
             mockRedis.expects('createClient').returns({});
    
             // Mock more methods as needed...
    
             return mockRedis;
         }
         return undefined;
     };
    
  3. You don't need to change your function code at all!

     exports.helloRedis = function (event, callback) {
       var redis = require('redis'); // this will be a mock
       cvar lient = redis.createClient();
    
       // ...
     };