-
Notifications
You must be signed in to change notification settings - Fork 115
Mocking function dependencies
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.
-
Enable the use of mocks:
functions config set useMocks true functions restart
-
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; };
-
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(); // ... };
Disclaimer: This is not an official Google product.
@google-cloud/functions-emulator is currently in pre-1.0.0 development. Before the 1.0.0 release, backwards compatible changes and bug fixes will bump the patch version number and breaking changes will bump the minor version number.