How to test if a function asserts in a NEAR smart contract (AssemblyScript)?

75 Views Asked by At

I have a function in my NEAR smart-contract (AssemblyScript) that I want to test. I want to test if the assertion actually happened.

AssemblyScript

foo(id: string): boolean {
  assert(id != 'bar', 'foo cannot be bar');
  return true;
}

Unit test (as-pect)

describe('Contract', () => {
  it('should assert', () => {
    contract.foo('bar'); // <-- How to test assertion here
  })
});

After running the above test, the console logs says

Failed: should assert - foo cannot be bar

I know I can return false or throw instead of doing an assert for the above example, and I may do that instead if it makes testing easier.

1

There are 1 best solutions below

0
On

use toThrow()

Like this:

describe('Contract', () => {
  it('should assert', () => {
    contract.foo('bar').toThrow('foo cannot be bar');
  })
});

you can also use not.toThrow() to test not trowing:

  it('should assert', () => {
    contract.foo('foo').not.toThrow();
  })
});