Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7496589
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T18:41:05+00:00 2026-05-29T18:41:05+00:00

Does anyone know how to test Mongoose Validations? Example, I have the following Schema

  • 0

Does anyone know how to test Mongoose Validations?

Example, I have the following Schema (as an example):

var UserAccount = new Schema({
    user_name       : { type: String, required: true, lowercase: true, trim: true, index: { unique: true }, validate: [ validateEmail, "Email is not a valid email."]  }, 
    password        : { type: String, required: true },
    date_created    : { type: Date, required: true, default: Date.now }
}); 

The validateEmail method is defined as such:

// Email Validator
function validateEmail (val) {
    return /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(val);
}

I want to test the validations. The end result is that I want to be able to test the validations and depending on those things happening I can then write other tests which test the interactions between those pieces of code. Example: User attempts to sign up with the same username as one that is taken (email already in use). I need a test that I can actually intercept or see that the validation is working WITHOUT hitting the DB. I do NOT want to hit Mongo during these tests. These should be UNIT tests NOT integration tests. 🙂

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T18:41:09+00:00Added an answer on May 29, 2026 at 6:41 pm

    I had the same problem recently.

    First off I would recommend testing the validators on their own. Just move them to a separate file and export the validation functions that you have.

    This easily allows your models to be split into separate files because you can share these validators across different models.

    Here is an example of testing the validators on their own:

    // validators.js
    exports.validatePresenceOf = function(value){ ... }
    exports.validateEmail = function(value){ ... }
    

    Here is a sample test for this (using mocha+should):

    // validators.tests.js
    var validator = require('./validators')
    
    // Example test
    describe("validateEmail", function(){
       it("should return false when invalid email", function(){
           validator.validateEmail("asdsa").should.equal(false)
       })      
    })
    

    Now for the harder part 🙂

    To test your models being valid without accessing the database there is a validate function that can be called directly on your model.

    Here is an example of how I currently do it:

    describe("validating user", function(){  
      it("should have errors when email is invalid", function(){
        var user = new User();
        user.email = "bad email!!" 
        user.validate(function(err){      
          err.errors.email.type.should.equal("Email is invalid")
        })
      })
    
      it("should have no errors when email is valid", function(){
        var user = new User();
        user.email = "test123@email.com"
        user.validate(function(err){
          assert.equal(err, null)
        })
      })
    })   
    

    The validator callback gets an error object back that looks something like this:

    { message: 'Validation failed',
        name: 'ValidationError',
        errors: 
            { email: 
               { message: 'Validator "Email is invalid" failed for path email',
                 name: 'ValidatorError',
                 path: 'email',
                 type: 'Email is invalid' 
               } 
            } 
    }
    

    I’m still new to nodeJS and mongoose but this is how I’m testing my models + validators and it seems to be working out pretty well so far.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a form with an input ( #test ). Does anyone know how
The following test fails. r1 seems to be missing angle brackets, does anyone know
Does anyone know how to test for the first member and last member in
Does anyone know a good way to test if one element, stored in a
Does anyone know of a good tool to test load and stress on webservices?
Does anyone know ways of partially or fully automating driver test installation? I am
Does anyone know of an existing browser/OS useragent string grid? It's hard to test,
Does anyone know how to test private functions in a Silverlight Unit Test project
does anyone know how to test when the last character in a UISearchBar is
Does anyone know if it is possible to test remote procedure calls in Cairngorm

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.