Tools for Promises Unit Testing
Basic Promise Code
Lets have a look at the below code. It has very simple function called
basic and returns the promise data after 1.6 seconds (Assume that its retrieved from Database after 1.6 seconds).
Unit Testing Basics
As explained in the previous step, Adding Mocha and Chai for this basic Promise Code. In order to write basic unit testing in mocha, understanding this below two methods is must.
- describe - This function helps to groups selected test cases. so its easy to refer and maintain.
- it - This function helps to write your use case and test your library / module and expect the result.
There is few more functions which are considered as Hooks. below are the four important hooks where this can be place inside
describe function before any
- before - runs before all tests in this block.
- beforeEach - runs before each test in this block.
- afterEach - runs after each test in this block.
- after - runs after all tests in this block.
Unit Testing example, We have main group
Basic Testing and three sub groups
Success Case and each sub groups has one test case. Scroll this Code below to get basic understanding.
If you are still not clear, then have a look at below explaination about each test cases.
- Basic - We are testing whether
basicis a function.
- Error Case -
basicshould return "Failure", when there is no parameter passed to the function.
- Success Case -
basicshould return given parameter as a result for success scenario.
Cool. If you noticed the Success Case and Error Case Scenario, We have used
returnkeyword for Promise method, so that it can wait and complete the operation. Its suggested to
done()for these types of test cases.
Lets see different example where it included external file which is Database library.