[Ethereum] Testing a function in Solidity from Truffle test using Javascript

truffle

I have the following contract:

contract C {

  address owner;
  address bigboss;

  modifier onlyOwner() {
    require(msg.sender==bigboss);
    _;
  }

  function C() {
    owner = msg.sender;
    bigboss = msg.sender;
  }

  function changeOwner(address _newAccount) onlyOwner {
    owner = _newAccount;
  }

}

So, I'm using truffle and Javascript to test creation of the contract, and testing of change of ownership.

const C = artifacts.require('C.sol');

var account_finance = 0x123456; // finance
var account_main = 0x7890abc; // main

contract('C', (accounts) => {
  payroll = new C({from: account_main});
  payroll.changeOwner({from: account_main}).call(account_finance);
});

I get this error:

TypeError: Cannot read property 'call' of undefined

What's wrong? Why couldn't I call changeOwner? Is my code correct?

Thank you.

Best Answer

First, in order to interact with a contract in your test, you need to have access to the deployed contract on the network. Simply instantiating it with new won't make the contract deployed to the network to start transactions. The way to do this is like so:

contract('C', (accounts) => {
  C.deployed().then(payroll => {
    // now you can use payrole as you wish inside here
  })
});

Another issue is that you are actually calling the changeOwner function wrong.

Instead of

payroll.changeOwner({from: account_main}).call(account_finance);

You probably wanted to use this:

payroll.changeOwner.call(account_finance, {from: account_main});

Also, you don't need to invoke the call method on changeOwner, you can directly invoke changeOwner() like this:

payroll.changeOwner(account_finance, {from: account_main});

The difference between the two forms is actually in the value that is resolved by the Promise they return. The first one would return the resolve to the value returned by the changeOwner function defined in the Contract, while the second one would return the current block that was mined to execute that function.

Related Topic