From dbaac9c692678523a7843c973d1519a9c1bb4aac Mon Sep 17 00:00:00 2001 From: Sigurd Fosseng Date: Fri, 27 Sep 2019 14:06:33 +0200 Subject: [PATCH] warn on unsupported formats --- src/__fixtures__/test.openapi.json | 33 ++++++++++++++++++++++++++++++ src/ajvCompile.ts | 24 ++++++++++++++-------- src/toMatchApiResponse.test.ts | 8 ++++++++ 3 files changed, 56 insertions(+), 9 deletions(-) diff --git a/src/__fixtures__/test.openapi.json b/src/__fixtures__/test.openapi.json index c450e1d..1dcd9f0 100644 --- a/src/__fixtures__/test.openapi.json +++ b/src/__fixtures__/test.openapi.json @@ -53,8 +53,28 @@ } } } + }, + "/unknown": { + "get": { + "operationId": "getUnknwon", + "summary": "Get metadata from the root of the API", + "tags": ["Metadata"], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnknownFormat" + } + } + } + } + } + } } }, + "components": { "schemas": { "Int32Number": { @@ -100,6 +120,19 @@ } }, "required": ["nullable"] + }, + "UnknownFormat": { + "type": "object", + "properties": { + "unknown": { + "type": "string", + "format": "programId" + }, + "url": { + "type": "string", + "format": "url" + } + } } } } diff --git a/src/ajvCompile.ts b/src/ajvCompile.ts index 4993f2e..6768070 100644 --- a/src/ajvCompile.ts +++ b/src/ajvCompile.ts @@ -1,21 +1,27 @@ -import Ajv, { NumberFormatDefinition } from "ajv"; +import Ajv, { NumberFormatDefinition, Options } from "ajv"; /** * @param schema dereferenced schema */ -export const ajvCompile = (schema: any) => { +export const ajvCompile = ( + schema: any, + { + unknownFormats = "ignore", + nullable = true, + jsonPointers = true, + ...rest + }: Options = {} +) => { const ajv = new Ajv({ - /** - * TODO: Add custom format supports for following formats. - * Maybe add formats from ajv-oai? https://git.io/fj4gs - */ - unknownFormats: ["float", "double", "byte", "binary", "password"], - nullable: true, - jsonPointers: true + unknownFormats, + nullable, + jsonPointers, + ...rest }); // custom formats ajv.addFormat("int32", isInt32); ajv.addFormat("int64", isInt64); + ajv.addFormat("url", ""); // the url format is wrong and deprecated const clone = JSON.parse(JSON.stringify(schema)); transformNullable(clone); diff --git a/src/toMatchApiResponse.test.ts b/src/toMatchApiResponse.test.ts index 20c6198..b734f13 100644 --- a/src/toMatchApiResponse.test.ts +++ b/src/toMatchApiResponse.test.ts @@ -20,4 +20,12 @@ describe("api responses", () => { await expect(response).toMatchApiResponse(testApi, "get", "/number"); await expect(response).not.toMatchApiResponse(testApi, "get", "/"); }); + it("GET /unkown", async () => { + const response: IApiResponse = { + body: { unknown: "xxx000000", url: "/something" }, + status: 200, + type: "application/json" + }; + await expect(response).toMatchApiResponse(testApi, "get", "/unknown"); + }); });