1+ import Ajv from 'ajv' ;
12import deepEqual from 'deep-equal' ;
23import { RESPONSE_CODE_REASONS } from 'insomnia/src/common/constants' ;
34import { sendCurlAndWriteTimelineError , type sendCurlAndWriteTimelineResponse } from 'insomnia/src/network/network' ;
@@ -216,6 +217,20 @@ export class Response extends Property {
216217 ) ;
217218 const haveBody = ( expected : string , checkEquality : boolean ) => verify ( this . text ( ) , expected , checkEquality ) ;
218219 const haveJsonBody = ( expected : object , checkEquality : boolean ) => verify ( this . json ( ) , expected , checkEquality ) ;
220+ const haveJsonSchema = ( expected : object , checkEquality : boolean ) => {
221+ const ajv = new Ajv ( ) ;
222+
223+ try {
224+ const jsonBody = JSON . parse ( this . body ) ;
225+ const schemaMatched = ajv . validate ( expected , jsonBody ) ;
226+ if ( ( schemaMatched && checkEquality ) || ( ! schemaMatched && ! checkEquality ) ) {
227+ return ;
228+ }
229+ } catch ( e ) {
230+ throw Error ( `Failed to verify response body schema, response could not be a valid json: "${ e } "` ) ;
231+ }
232+ throw Error ( "Response's schema is not equal to the expected value" ) ;
233+ } ;
219234
220235 return {
221236 // follows extend chai's chains for compatibility
@@ -224,13 +239,15 @@ export class Response extends Property {
224239 header : ( expected : string ) => haveHeader ( expected , true ) ,
225240 body : ( expected : string ) => haveBody ( expected , true ) ,
226241 jsonBody : ( expected : object ) => haveJsonBody ( expected , true ) ,
242+ jsonSchema : ( expected : object ) => haveJsonSchema ( expected , true ) ,
227243 } ,
228244 not : {
229245 have : {
230246 status : ( expected : number | string ) => haveStatus ( expected , false ) ,
231247 header : ( expected : string ) => haveHeader ( expected , false ) ,
232248 body : ( expected : string ) => haveBody ( expected , false ) ,
233249 jsonBody : ( expected : object ) => haveJsonBody ( expected , false ) ,
250+ jsonSchema : ( expected : object ) => haveJsonSchema ( expected , false ) ,
234251 } ,
235252 } ,
236253 } ;
0 commit comments