Skip to content

Commit

Permalink
Fix ref with alt. Closes #270
Browse files Browse the repository at this point in the history
  • Loading branch information
Eran Hammer committed Apr 21, 2014
1 parent 0986136 commit 3f0ac6a
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
6 changes: 5 additions & 1 deletion lib/alternatives.js
Expand Up @@ -48,7 +48,11 @@ internals.Alternatives.prototype.try = function (/* schemas */) {
var obj = this.clone();

for (var i = 0, il = schemas.length; i < il; ++i) {
obj._inner.push(Cast.schema(schemas[i]));
var cast = Cast.schema(schemas[i]);
if (cast._refs.length) {
obj._refs = obj._refs.concat(cast._refs)
}
obj._inner.push(cast);
}

return obj;
Expand Down
53 changes: 52 additions & 1 deletion test/ref.js
Expand Up @@ -167,7 +167,7 @@ describe('ref', function () {
b: Joi.number
});

ab.validate({ b:'6' }, function (err, value) {
ab.validate({ b: '6' }, function (err, value) {

expect(err).to.not.exist;
expect(value).to.deep.equal({ a: 6, b: 6 });
Expand All @@ -186,6 +186,57 @@ describe('ref', function () {
});
});

it('ignores the order in which keys are defined with alternatives', function (done) {

var a = { c: Joi.number };
var b = [Joi.ref('a.c'), Joi.ref('c')];
var c = Joi.number;

Validate({ a: a, b: b, c: c }, [
[{ a: {} }, true],
[{ a: { c: '5' }, b: 5 }, true],
[{ a: { c: '5' }, b: 6, c: '6' }, true],
[{ a: { c: '5' }, b: 7, c: '6' }, false]
]);

Validate({ b: b, a: a, c: c }, [
[{ a: {} }, true],
[{ a: { c: '5' }, b: 5 }, true],
[{ a: { c: '5' }, b: 6, c: '6' }, true],
[{ a: { c: '5' }, b: 7, c: '6' }, false]
]);

Validate({ b: b, c: c, a: a }, [
[{ a: {} }, true],
[{ a: { c: '5' }, b: 5 }, true],
[{ a: { c: '5' }, b: 6, c: '6' }, true],
[{ a: { c: '5' }, b: 7, c: '6' }, false]
]);

Validate({ a: a, c: c, b: b }, [
[{ a: {} }, true],
[{ a: { c: '5' }, b: 5 }, true],
[{ a: { c: '5' }, b: 6, c: '6' }, true],
[{ a: { c: '5' }, b: 7, c: '6' }, false]
]);

Validate({ c: c, a: a, b: b }, [
[{ a: {} }, true],
[{ a: { c: '5' }, b: 5 }, true],
[{ a: { c: '5' }, b: 6, c: '6' }, true],
[{ a: { c: '5' }, b: 7, c: '6' }, false]
]);

Validate({ c: c, b: b, a: a }, [
[{ a: {} }, true],
[{ a: { c: '5' }, b: 5 }, true],
[{ a: { c: '5' }, b: 6, c: '6' }, true],
[{ a: { c: '5' }, b: 7, c: '6' }, false]
]);

done();
});

describe('#create', function () {

it('throws when key is missing', function (done) {
Expand Down

0 comments on commit 3f0ac6a

Please sign in to comment.