You can never understand everything but you should push yourself to understand the system.
-Ryan Dahl (creator of Node.JS)
This repository aims to explain the 'WHAT', 'WHY' and 'HOW' of MochaJS and ChaiJS in a simplifieid manner.
- What is Unit Testing?
- What is Mocha?
- What is Chai?
- Setup
- How to write Mocha Tests?
describe()
it()
before()
andbeforeEach()
after()
andafterEach()
only()
assert()
should()
expect()
- Difference between
assert()
,should()
andexpect()
. - What is TDD?
- Useful Links.
- Think of them as first safety net for catching bugs in the production code. They are means to validate test cases for individual functions. That is all there is to it!
- Also keep in mind unit test should run fast. We ideally want a developer re-running the unit test every three to five minutes and this can be difficult with a slow build process or if any of the tests runs slow, an example, more than a just a few seconds.
Mocha is a JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting.
Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.
1. Initiate a npm project.
`npm init`
2. Installing Mocha
`npm i -g --save-dev mocha`
3. Installing Chai
`npm i -g --save-dev chai`
Note: save-dev saves it as a dev dependency
4. In the package.json file assign the value of 'mocha' to test. It will be something like this.
`scripts": { "test" : "mocha" }`
5. Create a test folder. Add your tests into it.
6. Run all tests using `npm test`. Run individual test file using `mocha testfile.js`
They are commonly known as test suites, which contains test cases.
They are nothing more than merely groups, and you can have groups within groups.
You can nest it as deep as you want. Also see basic-test.js
above.
It is nothing but a test case.
They are also called as hooks. They are used to set preconditions.
before()
is run before all it/describe. beforeEach
is run before every it.
They are also called hooks and are used to clean up after test cases.
It ensures only the test cases in only block is executing.
NOTE Also see basic-test.js
above for example on each.
Explained via code in assert-test-example.js
Explained via code in should-test-example.js
Explained via code in expect-test-example.js
assert()
follows a TDD style assertion. expect()
and should()
both follow BDD style. Both use the same chainable language to construct assertions, but they differ in the way an assertion is initially constructed. In the case of should, there are also some caveats and additional tools to overcome the caveats. Moreover, expect()
require is just a reference to the expect()
function, whereas with the should()
require, the function is being executed.
Explained via code in tdd-test-example.js