Search code examples
ethereumsolidityweb3js

How to simulate block minting in smart contracts unit test?


I am writing a smart contract for staking. Earnings are increased each time a new block is minted. In order to test the calculation of earnings, I need to simulate a certain number of blocks to be minted in my test suite. Is there a function in web3.js to do this?


Solution

  • Web3js is "just" a wrapper for RPC method calls to the node, so the exact method depends on your node emulator.

    However most emulators implement the evm_mine RPC method allowing you to mine an empty block within the emulator network.

    web3.currentProvider.send({
        jsonrpc: "2.0",
        method: "evm_mine",
        id: 1
    }, (error, response) => {
        console.log(response);
    });
    

    Docs: