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

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.

2
  • 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 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. – Sergi Juanati Jan 31 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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