Solidity – How to Test Solidity Functions Dependent on block.timestamp

erc-20soliditytruffleweb3js

I am writing a smart contract for token staking in Solidity. Here is an example code snippet:

contract Test {
 
 uint lastStakeTime;
 
 function withdraw () {
  if (differenceBetween(lastStakeTime, block.timestamp, ONE_MONTH) {
     revert ("cannot withdraw before one month");
  }
  // Do something here
 }

}

Function checks the time difference of 1 month as withdraw condition and reverts. How do I simulate this using Truffle and web3js?

I need to make below test pass:

it ('cannot withdraw before one month', async() => {
    
    // expecting to revert
    truffleAssert.reverts(Test.withraw(withdrawAmount, {from: accounts[0]}), 
    'cannot withdraw before one month');
  })

Best Answer

You can download Openzeppelin test-helpers,Here is the doc

Helpers to convert different time units to seconds. Available helpers are: seconds, minutes, hours, days, weeks and years

example: await time.increase(time.duration.hours(1));