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 3 comments
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.


  1. Such an awesome article, these many days, doubts in multiple concepts were bothering me, I started searching through books and net, but doubt was not cleared, thank you so much for providing this article, helped me a lot
    software testing training in chennai

  2. This kind of great write-up, these kinds of many days, questions inside numerous principles have been annoying myself, i started out seeking by means of guides and also homepage , yet uncertainty had not been eliminated, many thanks a great deal regarding offering this informative article, aided myself a whole lot.

  3. Such an wonderful content, these kind of a number of days, concerns throughout a number of aspects ended up worrying us, Devops As a Service i commenced browsing by way of textbooks along with world wide web, nevertheless hesitation has not been cleaned, thanks a lot much pertaining to delivering this information, made it easier for us a good deal.