Truffle – How to Test a Call with Arguments in Truffle.js

truffletruffle-test

I am trying to testa a smart contract function that receives an arg. I'm using truffle javascript tests, this is the smart contract function, very simple:

function addExam(string memory hash) public returns (string memory examProfessorHash) {
        // save the exam hash and link it with the professors address
        professorsExam[msg.sender] = hash;

        return hash;
    }

As you can see, it receives a hash as an argument. Now I want to test this in Truffle js:

 it("should add an exam to the exams list", async () => {
        // This should test the complete functionality
        let hash_test = "fB03aA5E2E71De1470ae2";
        let instance = await Exam.deployed();
        let hash = instance.addExam().call(hash_test, {from: accounts[0]});
        assert.equal(hash.valueOf(), hash_test, "Not returning the correct address")
    })

I can improve the test of course, but first, I need to be able to call the function and pass it an argument, how do I do that? The code above doesnt work, it gives me an error:

Error: Invalid number of parameters for "addExam". Got 0 expected 1!

Best Answer

You have two different issues here:

First, the syntax addExam().call(...) is incorrect.

It should be either addExam.call(...) or addExam(...).

Second, the usage of call by itself is incorrect.

Since function addExam changes the state of your contract, you should use sendTransaction.


In short, change this:

instance.addExam().call(hash_test, {from: accounts[0]})

To this:

instance.addExam.sendTransaction(hash_test, {from: accounts[0]})

Or to this:

instance.addExam(hash_test, {from: accounts[0]})
Related Topic