Sponsored by Gluten Free Waffles and Sliced Bananas

Tuesday, August 19, 2014

Unit Testing Mongoose Model Pre-validate Hooks (Middleware) using Mocha

8:35 AM Posted by Tyson Nero 1 comment
Unit testing Mongoose models is a very trivial task in general. Where it is not entirely that difficult to implement, trying to understand the ins and outs is tedious especially when there is little documentation or code examples of such. In this article, I am going to show how you can unit test "pre-validate" hooks on Mongoose models using Mocha and Chai.

Here is the model we will be testing:

This model will have  pre-validate hook for checking the password strength. Note: this code uses the OWASP Password Strength Test plugin. Notice that in this snippet, we are actually invalidating the document (this.invalidate()). This is the key part.

In using the pattern of the pre-validate hook actually invalidating the document, the unit tests become quite easy. In the tests, we will simply call validate() on the model, then check if the model has a populated errors array.

Unit testing Mongoose pre-validate hooks should be as simple as that.