How do I go about testing the following fallback function:

function () public payable {

being that the function does not have a function name, what do I need to do to test it? I tried using a function name that does not exist like this:

it("should not accept ETH deposits", async function() {
  let xferAmt = web3.toWei(0.5, "ether");
  await contract.dummyfunction({value: xferAmt}).should.be.rejectedWith(EVMThrow);

But truffle complains about the dummyfunction not being a function.

Thanks. A.


function () public {}


it("should not accept ETH deposits", async function() {
  let xferAmt = 1;
  await contract.sendTransaction({value: xferAmt}).should.be.rejectedWith(EVMThrow);
  • you should use contract.send
    – mirg
    Jun 15 '18 at 11:56
  • What version of web3js are you using? 0.2 or 1.0? Jun 15 '18 at 11:56
  • @mirg - I tried contract.send and then got a strange error: new BigNumber() not a number: [object Object] which is odd. as there is a only a revert
    – adam
    Jun 15 '18 at 12:02
  • @Andromelus - whatever comes with truffle.. looks like "0.18.4"
    – adam
    Jun 15 '18 at 12:04

Make the fallback function:

function () public {
  // dont receive ether via fallback method (by not having 'payable' modifier on this function). 

See OpenZeppelin examples: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/HasNoEther.sol

And test it with sendTransaction:

it("...should reject sending ether directly to the contract.", async () => {
  instance = await Contract.deployed();
  await assertRevert(
      { from: myAddress, value: 1 }

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.