This repository was archived by the owner on Nov 8, 2024. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change @@ -148,6 +148,27 @@ function getBodyValidator(realType, expectedType) {
148
148
return [ null , validator [ 0 ] ] ;
149
149
}
150
150
151
+ /**
152
+ * Parses a given JSON Schema to ensure it's a valid JSON.
153
+ * @param {string } schema
154
+ */
155
+ const validateJsonSchema = ( schema ) => {
156
+ try {
157
+ JSON . parse ( schema ) ;
158
+ } catch ( error ) {
159
+ throw new Error ( `\
160
+ Failed to parse a given JSON Schema:
161
+
162
+ ${ schema }
163
+
164
+ Please check if that is a valid JSON and a valid JSON Schema.
165
+
166
+ Original parsing error:
167
+ ${ error . stack } \
168
+ ` ) ;
169
+ }
170
+ } ;
171
+
151
172
/**
152
173
* Validates given bodies of transaction elements.
153
174
* @param {Object<string, any> } expected
@@ -170,6 +191,13 @@ function validateBody(expected, real) {
170
191
real . headers && real . headers [ 'content-type' ] ,
171
192
'real'
172
193
) ;
194
+
195
+ // Attempt to parse a given JSON Schema
196
+ // in case it's a raw string.
197
+ if ( typeof expected . bodySchema === 'string' ) {
198
+ validateJsonSchema ( expected . bodySchema ) ;
199
+ }
200
+
173
201
const [ expectedTypeError , expectedType ] = expected . bodySchema
174
202
? getBodySchemaType ( expected . bodySchema )
175
203
: getBodyType (
Original file line number Diff line number Diff line change @@ -444,4 +444,32 @@ describe('validateBody', () => {
444
444
} ) ;
445
445
} ) ;
446
446
} ) ;
447
+
448
+ describe ( 'given malformed JSON schema' , ( ) => {
449
+ const getResult = ( ) =>
450
+ validateBody (
451
+ {
452
+ // Purposely invalid JSON Schema
453
+ bodySchema : `
454
+ {
455
+ "$schema": "http://json-schema.org/draft-04/schema#",
456
+ "type": "object",
457
+ "properties": {
458
+ "href"": {
459
+ "type": "string"
460
+ }
461
+ }
462
+ }
463
+ }
464
+ `
465
+ } ,
466
+ {
467
+ body : '{ "foo": "bar" }'
468
+ }
469
+ ) ;
470
+
471
+ it ( 'must throw with malformed JSON schema error' , ( ) => {
472
+ expect ( getResult ) . to . throw ( / ^ F a i l e d t o p a r s e a g i v e n J S O N S c h e m a : / g) ;
473
+ } ) ;
474
+ } ) ;
447
475
} ) ;
You can’t perform that action at this time.
0 commit comments