Search code examples
javascripttestingmocha.jssolidity

Solidity, Mocha AssertionError: Unspecified AssertionError


I'm learning how to unit test solidity code with mocha, and I get this error from simple code:

contract hello{
    function returnString() public pure returns(string memory){
        return "this";
    }
}

When testing without try/catch:

const Hello = artifacts.require('hello');

contract('hello', () => {

    it('should return string', async () => {
        const hello = await Hello.deployed();
        const result = hello.returnString();
        assert(result == "this");
    });
});

I get this error:

  Contract: hello
    1) should return string
    > No events were emitted


  0 passing (291ms)
  1 failing

  1) Contract: hello
       should return string:
     AssertionError: Unspecified AssertionError
      at Context.<anonymous> (test/Hello.js:15:3)
      at processTicksAndRejections (node:internal/process/task_queues:94:5)

But when I'm testing it with try/catch":

const Hello = artifacts.require('hello');

contract('hello', () => {
    it('should return string', async () => {
        const hello = await Hello.deployed();
        const result = hello.returnString();
        
        try { 
            assert(result === "this");
        }
        catch (e){
            console.log(e);
        }
        
    });
});

I get this one: (✓ should return string is green, meaning it passed test)

  Contract: hello
AssertionError: Unspecified AssertionError
    at Context.<anonymous> (/home/kaneda/Documents/learn/testing/contract_1/test/Hello.js:18:4)
    at processTicksAndRejections (node:internal/process/task_queues:94:5) {
  showDiff: false,
  actual: null,
  expected: undefined
}
    ✓ should return string


  1 passing (143ms)

So, what is this behaviour, is it actually passing test but throwing error or what? I'm a bit confused.


Solution

  • Oh, silly mistake, I forgot await before hello.returnString() in

    const result = hello.returnString();

    This explains why code was failing, but I still don't understand that try/catch behavior.