Skip to content

Commit

Permalink
Add ValidatorBuilder
Browse files Browse the repository at this point in the history
  • Loading branch information
Gnucki committed Jul 12, 2017
1 parent a7dbff3 commit 569614d
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/ValidatorBuilder.js
@@ -0,0 +1,32 @@
'use strict';

const constructor = Symbol('constructor');

module.exports = class ValidatorBuilder {
/**
* Class constructor.
*
* @type {function}
*
* @throws {TypeError} If given value is not a function.
*/
set classConstructor(value) {
if (typeof value !== 'function') {
throw new TypeError(`Class constructor must be a class constructor function, got a ${typeof value} instead`);
}
this[constructor] = value;
}

/**
* Build a validator.
*
* @param {function} validate - The validation function.
*
* @returns {Validator} A validator.
*/
build(validate) {
const validator = new this[constructor]();
validator.validationFunction = validate;
return validator;
}
};
33 changes: 33 additions & 0 deletions test/unit/ValidatorBuilder.js
@@ -0,0 +1,33 @@
'use strict';

const expect = require('../expect');
const ValidatorBuilder = require('../../src/ValidatorBuilder');

const builder = new ValidatorBuilder();
class Validator {}

describe('ValidatorBuilder', () => {
describe('"classConstructor" setter', () => {
it('shoud accept a function', () => {
builder.classConstructor = value => value;
});

it('shoud only accept a function', () => {
expect(() => { builder.classConstructor = 'foo'; }).to.throw(TypeError);
});
});

describe('"build" method', () => {
before(() => {
builder.classConstructor = Validator;
});

it('shoud return an instance of classContructor', () => {
expect(builder.build()).to.be.an.instanceof(Validator);
});

it('shoud pass first argument to validator validationFunction', () => {
expect(builder.build(2)).to.have.property('validationFunction', 2);
});
});
});

0 comments on commit 569614d

Please sign in to comment.