Skip to content

Commit

Permalink
test: add coverage for inheritance re: #7045
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Dec 13, 2018
1 parent 1d12a53 commit aede9d1
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/cast/date.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const assert = require('assert');

module.exports = function castDate(value) {
// Support empty string because of empty form values. Originally introduced
// in https://github.com/Automattic/mongoose/commit/efc72a1898fc3c33a319d915b8c5463a22938dfe
// in https://github.com/Automattic/mongoose/commit/efc72a1898fc3c33a319d915b8c5463a22938dfe
if (value == null || value === '') {
return null;
}
Expand Down
5 changes: 3 additions & 2 deletions lib/schema/objectid.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,11 @@ ObjectId._cast = castObjectId;
*
* ####Example:
*
* // Make Mongoose only try to cast strings
* // Make Mongoose only try to cast length 24 strings. By default, any 12
* // char string is a valid ObjectId.
* const original = mongoose.ObjectId.cast();
* mongoose.ObjectId.cast(v => {
* assert.ok(v == null || typeof v === 'string');
* assert.ok(typeof v !== 'string' || v.length === 24);
* return original(v);
* });
*
Expand Down
30 changes: 29 additions & 1 deletion test/schematype.cast.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,34 @@ describe('SchemaType.cast() (gh-7045)', function() {
Schema.Types.Date.cast(original.date);
});

it('with inheritance', function() {
class CustomObjectId extends Schema.ObjectId {}

CustomObjectId.cast(v => {
assert.ok(v == null || (typeof v === 'string' && v.length === 24));
return original.objectid(v);
});

const objectid = new CustomObjectId('test', { suppressWarning: true });
const baseObjectId = new Schema.ObjectId('test', { suppressWarning: true });

let threw = false;
try {
objectid.cast('12charstring');
} catch (error) {
threw = true;
assert.equal(error.name, 'CastError');
}

objectid.cast('000000000000000000000000'); // Should not throw

// Base objectid shouldn't throw
baseObjectId.cast('12charstring');
baseObjectId.cast('000000000000000000000000');

assert.ok(threw);
});

it('handles objectid', function() {
Schema.ObjectId.cast(v => {
assert.ok(v == null || typeof v === 'string');
Expand All @@ -31,7 +59,7 @@ describe('SchemaType.cast() (gh-7045)', function() {

let threw = false;
try {
objectid.cast(123);
objectid.cast({ toString: () => '000000000000000000000000' });
} catch (error) {
threw = true;
assert.equal(error.name, 'CastError');
Expand Down

0 comments on commit aede9d1

Please sign in to comment.