Truffle Testing – Fixing TypeError: MyFunction is Not a Function Issue

testingtestrpctruffle

I'm using truffle and testrpc to check whether my addMember function works or not.

And here is my contract code.

/*make Stakeholder*/
function addMember(bytes32 _name, uint256 _threshold, uint256 _fund, uint _rate, bytes32 _character){
    uint id;
    address targetStakeholder = msg.sender;
    if (stakeholderId[targetStakeholder] == 0) {

       stakeholderId[targetStakeholder] = stakeholders.length;
       id = stakeholders.length++;
       stakeholders[id].name=_name;
       stakeholders[id].threshold=_threshold;
       stakeholders[id].fund=_fund;
       stakeholders[id].id=id;
       stakeholders[id].rate=_rate;
       stakeholders[id].addr=msg.sender;
       stakeholders[id].since=now;
       stakeholders[id].character= _character;
    } else {
        id = stakeholderId[targetStakeholder];
        Stakeholder m = stakeholders[id];
    }

    MembershipChanged(targetStakeholder, true);
}

And the following is my truffle test code.

contract('Congress', function(accounts) {
  it("adding new member", function() {
    var temp = Congress.deployed();
    return temp.addMember("John", 100, 100, 50, "buyer", {from:accounts[1]}).then(function(txs){
      console.log(txs);
    });
  });
});

However, the truffle console shows me the error message

TypeError: temp.addMember is not a function

And I just can't figure out why.

Any suggestion is appreciated.
Thank you so much!

Best Answer

Assuming your successfully deployed the contract with $ truffle migrate --reset ... Need to reset every time you start testrpc.

I think the problem is it's asynchronous and you're not waiting for Congress.deployed(); to finish.

I'm not up to full speed in 3.x due to the breaking changes, but based on what I've read in http://truffleframework.com/tutorials/upgrading-from-truffle-2-to-3#contract-abstractions-deployed-is-now-thennable, deployed is now thennable, so something like ...

var congress;    
contract('Congress', function(accounts) {
  it("adding new member", function() {
    Congress.deployed() // wait for the response
    .then(function(temp) {
      congress = temp;
      return congress.addMember("John", 100, 100, 50, "buyer", {from:accounts[1]});
    })
    .then(function(txn){
      console.log(txn);
      // carry on
    });
  });
});

Hope it helps.

Related Topic