To do unit testing in node we will be using mocha for running test cases and chai for BBD styles test cases.
STEP 1: Install Dependency
npm install mocha
npm install chai
npm install chai-http
STEP 2: Initialize test File
Getting Ready Test File
require chai, chai-http and require file which starts your server
add mocha test in scripts in package.json to run test cases
Step 3: Writing Test
As to be able to run only one test case at a time we can create an object with a unique key and assigning values true and false and we can use those object values to allow the test case to run only when the respective object key value to true by checking with if condition.Note if condition by default check for true no need to specify like this (test case.addObject == true). We can define our test content type with .set to form-url encoded or application/JSON as required. Here Application/JSON will be used
Creating Object with unique key and value. As our code to be tested is an async function we need to set the parameter of it block function to done so that when mocha sees that our it block has a test case
test for add person
As the function we are testing is an async function we need to specify done in our test case
We can group the test case in a single function to make it more organize and distinguish from other unrelated test cases like this:
add Favourite and get Favourite
Step 4: *Running Test
*
Now run the test case
npm test
Top comments (0)