Skip to Content
Learn
Model Testing Patterns
Path Validation II

Your test passes and the model technically satisfies the DDZC’s no-more-than-10 regulation. But as it currently exists, there are two issues:

  • the validation error message is not helpful, and
  • the validation function will invalidate a count of any value.

Before you write the code to fix the issues, you’ll need more failing tests.

Remember that validation error messages are defined in the schema like this:

age: { type: Number, validate: [validator, 'Age must be above 9.'] }

And you can assert the value of multiple properties of [instance].errors.[path] like message, path, kind, and name. You can write out multiple assertions or use assert.include:

const errorInfo = person.errors.age; assert.include(errorInfo, { message: 'Age must be above 9.', path: 'age', kind: 'user defined', name: 'ValidatorError' });

The complete list of validators are available here: http://mongoosejs.com/docs/schematypes.html.

Instructions

1.

In dinosaur-test.js at the end of the 'is invalid with 11' test, assert that dino.errors.count.message strictly equals 'Cannot hold more than 10 dinosaurs.'.

2.

Run the test suite and see the error message:

AssertionError: expected 'Validator failed for path `count` with value `11`' to equal 'Cannot hold more than 10 dinosaurs.'
3.

Add the validation error message 'Cannot hold more than 10 dinosaurs.' in dinosaur.js. Don’t forget to use square [ ] brackets!

4.

Run the test suite and see green. Time to solve the second issue.

5.

In dinosaur-test.js below the is invalid with 11 test, add the following test.

it('is valid with 10', () => { const dino = new Dinosaur({ name: 'Triceratops', count: 10, risk: 'Low' }); dino.validateSync(); assert.isUndefined(dino.errors, 'model should be valid'); });
6.

Run the test suite and see red. This will drive the implementation of the validator function, which is currently invalidating every value.

7.

Change the validator function to look like this

const validator = function(value) { return value <= 10; };
8.

Run the test suite and see green!

9.

Time to refactor: The validator function can be replaced by a built-in validator provided by Mongoose, max. Replace the validate property with

max: [10, 'Cannot hold more than 10 dinosaurs.']
10.

Run the test suite and see green!

Folder Icon

Sign up to start coding

Already have an account?