I would avoid using javascript dates when working with Solidity. It's better to work with unix time directly. I've also been struggling with this and came up with this solution:
- use hardhat's network-helpers library to get the timestamp of the latest block
- use unix seconds to assert results
- use
assert.closeTo()
instead of assert.equalTo()
, this way you can factor in you code execution time
Here I've made a simple example where you have a contract which sets a variable to next week when setNextWeek()
is called. In the test we assert if the setNextWeek() function indeed set the time to next week.
Solidity
uint256 nextWeek;
function setNextWeek() public {
nextWeek = block.timestamp + 1 weeks;
}
Hardhat Test
const helpers = require("@nomicfoundation/hardhat-network-helpers")
const ONE_WEEK_UNIX = 604800 // 1 week in UNIX time (seconds)
it.only("setNextWeek should set UNIX time to 1 week from now", async function () {
await contract.setNextWeek()
const nextWeekResult = await contract.nextWeek()
const timestamp = parseInt(await helpers.time.latest());
const nextWeek = timestamp + ONE_WEEK_UNIX
// checks if the result is close to the expected result with a maximum difference of 5 (seconds)
assert.closeTo(nextWeekResult.toNumber(), nextWeek, 5);
}
require((now + 1 days) > created_at, "The created_at should be less than now .");
in smart contracts, the error is same.