class: title # Testing: Mocha and Asserts --- ## Agenda 1. Mocha Basics 2. Chai Basics 3. Introduction to Web3 4. More in depth: Testing Smart Contracts --- ## Mocha Basics ### Introduction - Mocha is used for setting up tests - Embark and Truffle have Mocha built in --- ## Mocha Hooks - suite callbacks (`describe`, `contract`) - before hook [suite] - beforeEach [test] - test callbacks (`it`) - afterEach [test] - after hook [suite] --- ## Mocha Async - For async callbacks, you can use the keyword `done()` - Using done twice will error out - A lot of calls in smart contracts are asynchronous - Mocha can be used with promises, async/await, done, and callbacks --- ## Chai Basics - Test Driven Development - `assert` - Behaviour Driven Development - `expect, should` --- ## Chai Basics ### Assert ```javascript assert (expression, message); ``` The expression above should evaluate to something that is true or false. ### Assert Strict Equal ```javascript assert.strictEqual (actual, expected, message); ``` The above tests strict equality between two inputs. --- ## Assert OK ```javascript assert.ok(value, message); ``` The above automatically evaluates to the value being true. --- ## Basic Web 3 Syntax ### Invoking Methods `contractName.methods.methodName().call();` `contractName.methods.varName().call();` - call is always used for data that is being read from the blockchain - for public variables and calling view functions. `contractName.methods.methodName().send();` - to send, we have to send arguments for web3 to determine how to make a call - `.send( { from: address } );` is an example --- ## Testing Requires - Wrap your call in a try-catch statement - Catch the error, and save the error message - Compare it to what you expect it should fail with --- ## Lab - Create a simple smart contract that uses a msg.sender verification pattern - Test the positive and the negative cases, ensuring to assert on all tests that are expected to revert