Skip to content

Commit

Permalink
Improve custom class validation
Browse files Browse the repository at this point in the history
  • Loading branch information
afsampaio authored and franciscocardoso committed Oct 30, 2020
1 parent d8e009d commit 8641b1b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
10 changes: 8 additions & 2 deletions src/asserts/callback-assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@
const _ = require('lodash');
const { Violation } = require('validator.js');

/**
* Constants.
*/

const expression = /^[a-zA-Z]+$/;

/**
* Export `CallbackAssert`.
*/
Expand All @@ -16,8 +22,8 @@ module.exports = function(fn, customClass) {
* Class name.
*/

if (_.isNil(customClass)) {
throw new Error('Callback must be instantiated with a custom class');
if (!_.isString(customClass) || !expression.test(customClass)) {
throw new Error('Callback must be instantiated with a valid custom class name');
}

this.__class__ = customClass;
Expand Down
18 changes: 10 additions & 8 deletions test/asserts/callback-assert.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,22 @@ const Assert = BaseAssert.extend({
*/

describe('CallbackAssert', () => {
it('should fail if `customClass` is missing', () => {
it('should throw an error if `customClass` is missing', () => {
try {
Assert.callback(value => value === 'foobiz').validate('foobar');
} catch (e) {
expect(e.message).toEqual('Callback must be instantiated with a custom class');
expect(e.message).toEqual('Callback must be instantiated with a valid custom class name');
}
});

it('should fail if `customClass` is `null`', () => {
try {
Assert.callback(value => value === 'foobiz', null).validate('foobar');
} catch (e) {
expect(e.message).toEqual('Callback must be instantiated with a custom class');
}
it('should throw an error if `customClass` is invalid', () => {
['foo bar', 'foo 1', '1', '{}', 1].forEach(customClass => {
try {
Assert.callback(value => value === 'foobiz', customClass).validate('foobar');
} catch (e) {
expect(e.message).toEqual('Callback must be instantiated with a valid custom class name');
}
});
});

it('should throw an error if `value` is missing', () => {
Expand Down

0 comments on commit 8641b1b

Please sign in to comment.