2

I am running some test in my first smart contract called Inbox.sol. I Want to call the method .message in order to see if it is equal to the default variable I use when I deploy the contract with web3.

My Inbox.sol code

pragma solidity >=0.6.12;

contract Inbox {
    string public message;

    function initialInbox(string memory initialMessage) public {
        message = initialMessage;
    }

    function setMessage(string memory newMessage) public {
        message = newMessage;
    }
}

My test file with Mocha is:

let accounts
let inbox

beforeEach(async () => {
  // Get a list of all accounts
  accounts = await web3.eth.getAccounts()
  // Use one of those account to deploy the contract
  inbox = await new web3.eth.Contract(abi)
    .deploy({ data: bytecode, arguments: [INITIAL_ARGUMENT]})
    .send({ from: accounts[0], gas: GAS})
})

describe(('Inbox'), () => {
  it("has a default message", async () => {
    const message = await inbox.methods.message() // Returns a big object
    console.log(message)
    const messageCalled = await inbox.methods.message().call()
    console.log(messageCalled) // Returns nothing
    assert.strictEqual(message, INITIAL_ARGUMENT)
  })
})
1
  • 1
    Please add a constructor function if you wish to store an initial value to the 'message' variable.
    – Akshay Dev
    Jul 26 '21 at 7:41
0

For the version that you are using you should be adding a constructor to your contract:

contract Inbox {
    string public message;

    constructor(string memory initialMessage) public {
        message = initialMessage;
    }

since "message" is a public variable, solidity sets its getter, so you can call it message()

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.