Skip to content

Commit 8641b1b

Browse files
afsampaiofranciscocardoso
authored andcommitted
Improve custom class validation
1 parent d8e009d commit 8641b1b

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

src/asserts/callback-assert.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@
77
const _ = require('lodash');
88
const { Violation } = require('validator.js');
99

10+
/**
11+
* Constants.
12+
*/
13+
14+
const expression = /^[a-zA-Z]+$/;
15+
1016
/**
1117
* Export `CallbackAssert`.
1218
*/
@@ -16,8 +22,8 @@ module.exports = function(fn, customClass) {
1622
* Class name.
1723
*/
1824

19-
if (_.isNil(customClass)) {
20-
throw new Error('Callback must be instantiated with a custom class');
25+
if (!_.isString(customClass) || !expression.test(customClass)) {
26+
throw new Error('Callback must be instantiated with a valid custom class name');
2127
}
2228

2329
this.__class__ = customClass;

test/asserts/callback-assert.test.js

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,20 +20,22 @@ const Assert = BaseAssert.extend({
2020
*/
2121

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

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

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

0 commit comments

Comments
 (0)