2

I have a function that is not passing my tests in JS but the function works as expected in Remix. Can you help me

contract.sol

function test1 () public view returns(bool){
    return(true);
}
function test2 () public returns(bool){
    return(true);
}

test.js

it("Works", async () => {
  const restaurant = await BiteChain.deployed();
  let test1 = await restaurant.test1({from:owner});
  assert.equal(test1, true, 'should return true...');
});

it("Doesn't work", async () => {
  const restaurant = await BiteChain.deployed();
  let test2 = await restaurant.test2({from:owner});
  assert.equal(test2, true, 'should return true...');
});

And then the result is

Contract: TestBiteChain
√ Works
1) Doesn't work
...
 1) Contract: TestBiteChain
  Doesn't work:
 AssertionError: should return true...: expected { Object (tx, receipt, ...)
 }  to equal true
 at Context.it (test\BiteChain.test.js:45:12)
 at process._tickCallback (internal/process/next_tick.js:68:7)
  • The return-value of a non-constant (non-view and non-pure) function can only be used on-chain (i.e., by other functions in the same contract or in other contracts). – goodvibration Jan 14 at 19:09
0

The problem you're encountering is that functions which modify the state of code won't directly return state when invoked from Web3. If you were to change test2's type to view or pure, your tests will pass as expected.

The expected way inspect status of chain-modifiying functions is in one of the following ways:

  1. revert, when the function fails
  2. don't revert when the function succeeds
  3. emit events to communicate updates
  4. call views afterwards to inspect the modified state
  • Ah! That's it. I need to modify state in one function, then use a getter view or pure function to verify the state change. Thank you. – Nanoshi Jan 14 at 20:24
  • Glad I could help. If you accept this answer, it will help others with similar problems find the answer. – Motoma Jan 15 at 21:06

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.