0

I have create a truffle project with this command:

truffle unbox react

Here is my smartcontract contracts/SimpleStorage.sol :

contract SimpleStorage {

   enum MyEnum {
      step1,
      step2,
      step3,
      step4
   }

   MyEnum private var1 = MyEnum.step3;

   function myfunction() external view returns (MyEnum) {
      return var1;
   }  
}

Here is my test file: test/simplestorage.js

const SimpleStorage = artifacts.require("./SimpleStorage.sol");

contract("SimpleStorage", accounts => {

  it("my test", async () => {
    const simpleStorageInstance = await SimpleStorage.deployed();

    const ret = await simpleStorageInstance.myfunction();
    assert.equal(ret, 2);
  });

});

My question is: Is there a way to access to Enum Structure in the test file. I would like to write something like that:

assert.equal(ret, MyEnum.step3);

Thanks

1
  • This is one area where foundry tests in solidity are better than truffle. Jan 26 at 20:02

2 Answers 2

0

The SimpleStorage contract abstraction has MyEnum as a property so you can do:

assert.equal(ret, SimpleStorage.MyEnum.step3);
0

You can add this in your truffle test file:

const MyEnum = {
    step1: 0,
    step1: 1,
    step2: 2,
    step3: 3
};

and then, you can use expressions like this:

assert.equal(ret, MyEnum.step3);

instead of using numbers 0 to 3.

3
  • Thanks but with this solution i will have a code redundancy. The tester can make a mistake in the definition of the Enum. Is there a way to automaticaly "import" the enum from the solidity source code ?
    – Bob5421
    Jan 31, 2021 at 17:29
  • The thing is that in JavaScript, enums do not exist like in other programming languages (C, Java). Therefore, you will have to create an equivalent object that represents the enumeration used in Solidity. You will certainly have to ensure that this object is exactly created as defined in Solidity. Jan 31, 2021 at 17:36
  • Truffle gives you access to the enums in the contract abstraction.
    – amal
    Jul 11, 2021 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.