Testing with Mocha/Chai Lab

Introduction

Note: This can be a pair programming activity or done independently.

Now that we've written a few tests in our Express application from the previous lesson, it's your turn to practice writing more tests using a more more complex version of our Candies app that uses mongo and has more functionality.

At the end of this lab, you should have test written to make sure our index works properly, our show pages return the information we need, we can update and post a candy with error handling, and we can delete a candy from our database.

Exercise

Requirements

  • Setup the app to run mocha, chai and sinon
  • Implement these tests:
GET /candies
  ✓ should return a 200 response
  ✓ should return an array
  ✓ should return all the records in the database

GET /candies/:id
  ✓ should return a 200 response
  ✓ should return an object containing fields name and color

POST /candies
  ✓ should return a 200 response
  ✓ should return a 422 response if the field color is wrong
  ✓ should return an error message if the color field is wrong
  ✓ should add a new candy to the database
  ✓ should return an error if the color is wrong

PUT /candies/:id
  ✓ should return a 200 response
  ✓ should update a candy document

DELETE /candies/:id
  ✓ should remove a candy document
  • If you include the model candy in your spec file, you can execute requests to MongoDB directly from the test file, allowing you to watch the database directly before or after an action made by a test

  • If you take a look at the model, there is a validation on the color field allowing only certain colors for the field "color"; we are testing this validation with a message and the http status

Bonus:

  • Add more validations in the models and add the tests for it
  • Add fields with different types and write tests for them

Starter code

The starter code contains an app with a candy controller and a mongoose model

Deliverable

This is the output you should get in the terminal:

CLI Chai output

Additional Resources