How to Mock Chainlink VRF Coordinator V2 and Aggregator V3 With Truffle (0.8.0)
Locally test your smart contracts

In this story, I’ll show you how to make local tests of your smart contracts that use Aggregator V3 and VRF Coordinator V2 in Truffle using mock contracts.
Initialize Project
First, let’s init
a fresh Truffle project and install Chainlink contracts.
truffle init vrf-aggregator-mock
cd vrf-aggregator-mock
npm i @chainlink/contracts
Next, we’ll need to create a test
directory and mock contracts under the contracts
directory where we will put our mock contracts for testing purposes.
mkdir contracts/test
touch contracts/test/VRFCoordinatorV2Mock.sol
touch contracts/test/MockV3Aggregator.sol
Windows natively don’t support touch command, so you can manually create these files.
Mock Contract Codes
VRFCoordinatorV2Mock.sol
MockV3Aggregator.sol
This file is the same as the file in Chainlink contracts in Github, yet it is not included in the release so we can’t import it as we do for VRF Coordinator mock, we copy it and change the import only.
Using Mocks from a Contract
Now we also need one more contract which is we will use these mocks from.
Create a file named Mock.sol
(or whatever your contract is, I’ll just stick with Mock) under the contracts
directory:
Configuration to Use Ganache as Development Network
Open truffle-config.js
and add a development
network.
development: { host: "127.0.0.1", port: 7545, network_id: "*", websockets: true},
Websockets must be true because we will use events to retrieve random words that are created by the VRF Coordinator and HttpProvider
doesn’t support it.
Deploying Contracts
Create a file named 2_deploy_mock.js
under the migrations directory.
Now let’s check everything is alright by running the deploy command.
truffle deploy
Summary
=======
> Total deployments: 4
> Final cost: 0.06800202 ETH
Testing Mock Contract
Create a file named mock.js
under the test directory (not under the contracts/test
):
Now let’s run our test.
truffle test
If everything is okay, you should be seeing something like that:
Contract: Mock
✔ should return random words (1166ms)
✔ should return price feed2 passing (1s)
That’s it, yay!. We mocked VRF Coordinator V2 and Aggregator V3.