Search code examples
soliditysmartcontractstruffle

Setting variable states before testing in Truffle


Can you set variables inside a smart contract before running your tests. I'm thinking of testing functions that won't pass when a variable has reached a certain number.

I.E.

1. Write a function that will only run when var_1 >= 800
2. Write a test where var_1 is = 799 and the test confirms the function fails
3. Write a test where var_1 is = 801 and the test confirms the function succeeds 

Solution

  • So, something like this?

    const { exptect } = require("chai");
    const { ethers } = require("hardhat");
    
    describe("contract test" () => {
      let contract;
      
       beforeEach(async () => {
        // Before each test, we create a new contract instance, this is to prevent contract modifications between tests, and having each test executed without the interference of contract modification other tests.
        let Contract = await ethers.getContractFactory("Contract");
        await contract = Contract.deploy();
        await contract.deployed();
       });
       
       // Write a test where var_1 is = 799 and the test confirms the function fails.
       it("Should fail if var_1 is = 799", async () => {
       
          // set var_1 value.
          const tx = await contract.setVar1(799);
          await tx.wait();
          
          // Test function excepts...
          ...
       });
    }