Truffle Testing – How to Return a Mapping in Truffle Test

testingtruffle

How would you guys call a mapping from a test and get the values?

This is the mapping that I have on my contract:

mapping(address => uint[29]) balanceOf;

It´s a mapping to an array of integers which reflects the different slots in the balance of the user. So, I´m trying to call directly from the myTest.js (truffle) but return me an error:

 TypeError: Cannot read property 'call' of undefined
  at Context.it (test/ovxet2.js:13:50)
  at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:188:7)

And I´m doing this action like below, using async/await:

    var balanceOf = await instance.balanceOf.call({from: [accounts[0]][0]});
    console.log(balanceOf);

And I´ve also tried call in another way to receive the whole array of integers:

var balanceOf = await instance.balanceOf.call({from: accounts[0]});
    console.log(balanceOf);

However, I have another tests written using promise chaining…and I´ve implemented the same ways in order to get those values but return me the same errors.

So, can truffle returns mappings? Or I have to create my own getter function in the contract (for testing purposes) and then call that function from the test?

Best Answer

You cannot return a mapping type. Among the several reasons: keys are never stored and cannot be retrieved. A mapping doesn't known if a key has data or not, and it should return the whole structure which is 2^256 addresses containing 32 bytes each.

If your contract has declared

mapping(address => uint[29]) public balanceOf;

The solidity compiler will create a getter with a single parameter that will accept an address.

var balance = await instance.balanceOf.call(account);
console.log(balance);