I am trying to test my contracts using the Truffle suite, along with Ganache.
Up until now, I have been testing contract functions which are restricted to view
only. Now, when I attempt to make changes to the contract state, I'm finding that the state is not actually being changed between function calls.
Consider the following simple contract:
pragma solidity ^0.4.24;
import "../OrderBook.sol";
contract IdManager {
uint256 newId;
function addId() public returns (uint256) {
newId++;
return newId;
}
}
All I wish to do is increment newId
and return its new value.
The code I have written to test this is:
const { getWeb3, getContractInstance, parseSignature } = require("./test_helper");
const web3 = getWeb3();
const getInstance = getContractInstance(web3);
contract('IdManager', (accounts) => {
let IdManager = getInstance('IdManager');
it('test addId()', async () => {
console.log(await IdManager.methods.addId().call());
console.log(await IdManager.methods.addId().call());
console.log(await IdManager.methods.addId().call());
});
});
The getInstance()
call is making use of Web3 v1.0
, based off this tutorial.
With the above test, I would expect the output to be:
1
2
3
But, I actually get:
1
1
1
Has anyone come across this issue before?
Edit0:
console.log(await IdManager.methods.newId().call());
should have been console.log(await IdManager.methods.addId().call());
—newId()
is now addId()
.
Edit1:
Taking goodvibration's advice, I have modified the example contract to be as follows:
contract IdManager {
uint256 public newId;
function addId() public {
newId++;
}
function getId() public view returns (uint256) {
return newId;
}
}
The test code has been altered to the following:
it('test addId()', async () => {
await IdManager.methods.addId().call();
console.log(await IdManager.methods.getId().call());
await IdManager.methods.addId().call();
console.log(await IdManager.methods.getId().call());
await IdManager.methods.addId().call();
console.log(await IdManager.methods.getId().call());
});
Unfortunately, my output is still showing that the state is not being preserved:
0
0
0
addId
anywhere in your test!!!!!newId()
should have beenaddId()
. Apologies.OrderBook
??? Is that possibly the old contract which you were trying to run this test with?