Truffle – Testen von Enum-Werten

Ich verwende Truffle , um einen einfachen Smart Contract zu entwickeln.

Ich habe folgenden Vertrag:

contract Puppy {

  enum State { good, bad }

  State public status;
  State public constant INITIAL_STATUS = State.good;

  function Puppy() {
    status = INITIAL_STATUS;
  }
}

Und ich möchte es wie folgt testen:

const Puppy = artifacts.require('./Puppy.sol')

contract('Puppy', () => {
  it('sets the initial status to \'good\'', () => Puppy.deployed()
    .then(instance => instance.status())
    .then((status) => {
      assert.equal(status, Puppy.State.good, 'Expected the status to be \'good\'')
    }))
})

Das wirftTypeError: Cannot read property 'good' of undefined

Wenn ich den Test umstelle

const Puppy = artifacts.require('./Puppy.sol')

contract('Puppy', () => {
  it('sets the initial status to \'good\'', () => Puppy.deployed()
    .then(instance => instance.status())
    .then((status) => {
      assert.equal(status, 0, 'Expected the status to be \'good\'')
    }))
})

es geht vorbei.

Wie beziehe ich mich enuminnerhalb des Tests auf das?

Antworten (2)

Nehmen wir den Testvertrag:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;

contract Test {
    enum Stages {
        stage_01,
        stage_02,
        stage_03,
        stage_04,
        stage_05
    }

    Stages public stage = Stages.stage_01;

    function setStage(Stages _stage) public {
        stage = _stage;
    }
}

und teste es so:

const TestContract = artifacts.require('Test');

contract('Test', function (accounts) {
    const owner = accounts[0];
    const txParams = { from: owner };

    beforeEach(async function () {
        this.testContract = await TestContract.new(txParams);
    });

    it('test initial stage', async function () {
        expect((await this.testContract.stage()).toString()).to.equal(TestContract.Stages.stage_01.toString());
    });

    it('assign custom stage', async function () {
        await this.testContract.setStage(TestContract.Stages.stage_05);
        expect((await this.testContract.stage()).toString()).to.equal(TestContract.Stages.stage_05.toString());
    });
    
    it('assign custom number to stage', async function () {
        await this.testContract.setStage(3); // take into account that enum indexed from zero
        expect((await this.testContract.stage()).toString()).to.equal(TestContract.Stages.stage_04.toString());
    });      
});