Published on

Truffle Conditionally Deploy Based on Environment


In a dApp I am working on the contract pulls in another contract which is called in certain scenarios. In other programming languages in this situation you would simply inject a mock of the dependency used by what you are testing. This is exactly what I did in my case.

The contract I depended on was in another repo and would have been inaccessible from the current repo. To get around this I made a new mock contract that implemented the same interface as the dependency I needed and just made the functions return dummy values. The problem now is how to I tell truffle to only deploy these mocks in the development environment (i.e. Ganache)?

After some searching I found that the truffle deployer function has the following signature with 2 additional optional parameters:

module.exports = function (deployer, network, accounts) {

Using this I created a new migration script which I called 999999_mocks.js which will be responsible for deploying all mocks for tests. This script looks as below:

const SomeMock1 = artifacts.require('SomeMock1')
const SomeMock2 = artifacts.require('SomeMock2')

module.exports = function (deployer, network, accounts) {
  if (network === 'development') {
    console.log('........................Deploying mocks........................')
  } else {
    console.warn("Not deploying as this is not the 'development' environment")