[Ethereum] Hardhat writing tests for contract that calls another contract

contract-deploymenthardhathardhat-deploytesting

Basically I need to use DAI stablecoin in my contract. I want to test it out so I have copied the DAI smart contract code and deployed it on my localhost. Everything works fine, but I can't write Hardhat tests to my code, because it doesn't know about the contract deployed on my localhost. How should I write the tests when using another contract in my contract?

    address daiContractAddress = 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0; // HOW TO GET THIS TO HARDHAT TESTS?

    function getDaiBalanceForOwner() external view returns(uint){
        IERC20 dai = IERC20(address(daiContractAddress ));
        return dai.balanceOf(msg.sender); //Error: Transaction reverted: function call to a non-contract account
    }

Best Answer

Final solution with help of @LauriPeltonen: I am just deploying my dai contract in beforeEach and then taking its address and passing it to the contract constructor.

Solidity:

address public daiContractAddress; 

constructor(address _daiContractAddress ) {
    daiContractAddress = _daiContractAddress;
}


function getDaiBalanceForOwner() external view returns(uint){
    IERC20 dai = IERC20(address(daiContractAddress));
    return dai.balanceOf(msg.sender);
}

EthersJS test:

beforeEach(async function () {
    dai = await ethers.getContractFactory("Dai"); 
    myContract= await ethers.getContractFactory("MyContract"); 
     
    dai = await dai.deploy(1); //deploying dai contract first
    
    myContract = await myContract.deploy(dai.address); //deploying my contract later using dai.address in constructor
  });

  describe("Deployment", function() {
    it("Should be able to implement usd dai stablecoin", async function() {
      expect(ethers.utils.formatEther(await myContract.getDaiBalanceForOwner())).to.equal("0.0");
    });
  });
Related Topic