Skip to content

Commit

Permalink
Add tests for single-document population transforms
Browse files Browse the repository at this point in the history
Signed-off-by: Ian Macalinao <me@ian.pw>
  • Loading branch information
macalinao committed Aug 12, 2014
1 parent 5a0d62a commit 025de86
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,10 @@ Model.prototype.transformPopulate = function(field, transformer) {
}

// Normalize
var single = false;
if (typeof pop === 'object' && !Array.isArray(pop)) {
pop = [pop];
single = true;
}

// Ensure array, as it isn't an object at this point
Expand Down Expand Up @@ -208,6 +210,9 @@ Model.prototype.transformPopulate = function(field, transformer) {
return done(err, subDoc);
});
}, function(err, result) {
if (single) {
result = result[0];
}
doc[field] = result;
next();
});
Expand Down
49 changes: 49 additions & 0 deletions test/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,41 @@ describe('Model', function() {
});
});

it('should synchronously populate-transform a document', function(done) {
User.transformPopulate('spouse', function(req, doc) {
doc.name = 'Tim';
});
User.applyTransforms(null, {
toObject: function() {
return {
spouse: {}
};
}
}, function(err, doc) {
expect(doc.spouse.name).to.equal('Tim');
done();
});
});

it('should asynchronously populate-transform a document', function(done) {
User.transformPopulate('spouse', function(req, doc, next) {
async.times(1, function() {
doc.name = 'Tim';
next();
});
});
User.applyTransforms(null, {
toObject: function() {
return {
spouse: {}
};
}
}, function(err, doc) {
expect(doc.spouse.name).to.equal('Tim');
done();
});
});

it('should synchronously populate-transform a document array', function(done) {
User.transformPopulate('friends', function(req, doc) {
doc.name = 'Tim';
Expand Down Expand Up @@ -98,5 +133,19 @@ describe('Model', function() {
});
});

it('should not transform a non-existent field', function(done) {
User.transformPopulate('dne', function(req, doc) {
doc.asdf = 'asdf';
});
User.applyTransforms(null, {
toObject: function() {
return {};
}
}, function(err, doc) {
expect(doc.asdf).to.be.undefined;
done();
});
});

});
});

0 comments on commit 025de86

Please sign in to comment.