@ehuelsmann/chai-openapi-response-validator 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,379 @@
1
+ # Chai OpenAPI Response Validator
2
+
3
+ [![downloads](https://img.shields.io/npm/dm/@ehuelsmann%2Fchai-openapi-response-validator)](https://www.npmjs.com/package/@ehuelsmann/chai-openapi-response-validator)
4
+ [![npm](https://img.shields.io/npm/v/@ehuelsmann%2Fchai-openapi-response-validator.svg)](https://www.npmjs.com/package/@ehuelsmann/chai-openapi-response-validator)
5
+ ![build status](https://github.com/openapi-library/OpenAPIValidators/actions/workflows/ci.yml/badge.svg)
6
+ ![style](https://img.shields.io/badge/code%20style-airbnb-ff5a5f.svg)
7
+ [![codecov](https://codecov.io/gh/openapi-library/OpenAPIValidators/branch/master/graph/badge.svg)](https://codecov.io/gh/openapi-library/OpenAPIValidators)
8
+ [![included](https://badgen.net/npm/types/@ehuelsmann%2Fchai-openapi-response-validator)](https://github.com/openapi-library/OpenAPIValidators/blob/master/packages/chai-openapi-response-validator/lib/index.ts)
9
+ [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/openapi-library/OpenAPIValidators/blob/master/CONTRIBUTING.md)
10
+
11
+ Use Chai to assert that HTTP responses satisfy an OpenAPI spec.
12
+
13
+ ## Problem 😕
14
+
15
+ If your server's behaviour doesn't match your API documentation, then you need to correct your server, your documentation, or both. The sooner you know the better.
16
+
17
+ ## Solution 😄
18
+
19
+ This plugin lets you automatically test whether your server's behaviour and documentation match. It extends the [Chai Assertion Library](https://www.chaijs.com/) to support the [OpenAPI standard](https://swagger.io/docs/specification/about/) for documenting REST APIs. In your JavaScript tests, you can simply assert [`expect(responseObject).to.satisfyApiSpec`](#in-api-tests-validate-the-status-and-body-of-http-responses-against-your-openapi-spec)
20
+
21
+ Features:
22
+
23
+ - Validates the status and body of HTTP responses against your OpenAPI spec [(see example)](#in-api-tests-validate-the-status-and-body-of-http-responses-against-your-openapi-spec)
24
+ - Validates objects against schemas defined in your OpenAPI spec [(see example)](#in-unit-tests-validate-objects-against-schemas-defined-in-your-OpenAPI-spec)
25
+ - Load your OpenAPI spec just once in your tests (load from a filepath or object)
26
+ - Supports OpenAPI [2](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md) and [3](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md)
27
+ - Supports OpenAPI specs in YAML and JSON formats
28
+ - Supports `$ref` in response definitions (i.e. `$ref: '#/definitions/ComponentType/ComponentName'`)
29
+ - Informs you if your OpenAPI spec is invalid
30
+ - Supports responses from `axios`, `request-promise`, `supertest`, `superagent`, and `chai-http`
31
+ - Use in [Mocha](#usage) and other test runners
32
+
33
+ ## Contributing ✨
34
+
35
+ If you've come here to help contribute - thanks! Take a look at the [contributing](https://github.com/openapi-library/OpenAPIValidators/blob/master/CONTRIBUTING.md) docs to get started.
36
+
37
+ ## Installation
38
+
39
+ [npm](http://npmjs.org)
40
+
41
+ ```bash
42
+ npm install --save-dev @ehuelsmann/chai-openapi-response-validator
43
+ ```
44
+
45
+ [yarn](https://yarnpkg.com/)
46
+
47
+ ```bash
48
+ yarn add --dev @ehuelsmann/chai-openapi-response-validator
49
+ ```
50
+
51
+ ## Importing
52
+
53
+ ES6 / TypeScript
54
+
55
+ ```typescript
56
+ import chaiResponseValidator from '@ehuelsmann/chai-openapi-response-validator';
57
+ ```
58
+
59
+ CommonJS / JavaScript
60
+
61
+ <!-- prettier-ignore -->
62
+ ```javascript
63
+ const chaiResponseValidator = require('@ehuelsmann/chai-openapi-response-validator').default;
64
+ ```
65
+
66
+ ## Usage
67
+
68
+ ### In API tests, validate the status and body of HTTP responses against your OpenAPI spec:
69
+
70
+ #### 1. Write a test:
71
+
72
+ ```javascript
73
+ // Set up Chai
74
+ import chai from 'chai';
75
+ const expect = chai.expect;
76
+
77
+ // Import this plugin
78
+ import chaiResponseValidator from '@ehuelsmann/chai-openapi-response-validator';
79
+
80
+ // Load an OpenAPI file (YAML or JSON) into this plugin
81
+ chai.use(chaiResponseValidator('path/to/openapi.yml'));
82
+
83
+ // Write your test (e.g. using Mocha)
84
+ describe('GET /example/endpoint', () => {
85
+ it('should satisfy OpenAPI spec', async () => {
86
+ // Get an HTTP response from your server (e.g. using axios)
87
+ const res = await axios.get('http://localhost:3000/example/endpoint');
88
+
89
+ expect(res.status).to.equal(200);
90
+
91
+ // Assert that the HTTP response satisfies the OpenAPI spec
92
+ expect(res).to.satisfyApiSpec;
93
+ });
94
+ });
95
+ ```
96
+
97
+ #### 2. Write an OpenAPI Spec (and save to `path/to/openapi.yml`):
98
+
99
+ ```yaml
100
+ openapi: 3.0.0
101
+ info:
102
+ title: Example API
103
+ version: 1.0.0
104
+ paths:
105
+ /example:
106
+ get:
107
+ responses:
108
+ 200:
109
+ description: Response body should be an object with fields 'stringProperty' and 'integerProperty'
110
+ content:
111
+ application/json:
112
+ schema:
113
+ type: object
114
+ required:
115
+ - stringProperty
116
+ - integerProperty
117
+ properties:
118
+ stringProperty:
119
+ type: string
120
+ integerProperty:
121
+ type: integer
122
+ ```
123
+
124
+ #### 3. Run your test to validate your server's response against your OpenAPI spec:
125
+
126
+ ##### The assertion passes if the response status and body satisfy `openapi.yml`:
127
+
128
+ ```javascript
129
+ // Response includes:
130
+ {
131
+ status: 200,
132
+ body: {
133
+ stringProperty: 'string',
134
+ integerProperty: 123,
135
+ },
136
+ };
137
+ ```
138
+
139
+ ##### The assertion fails if the response body is invalid:
140
+
141
+ ```javascript
142
+ // Response includes:
143
+ {
144
+ status: 200,
145
+ body: {
146
+ stringProperty: 'string',
147
+ integerProperty: 'invalid (should be an integer)',
148
+ },
149
+ };
150
+ ```
151
+
152
+ ###### Output from test failure:
153
+
154
+ ```javascript
155
+ AssertionError: expected res to satisfy API spec
156
+
157
+ expected res to satisfy the '200' response defined for endpoint 'GET /example/endpoint' in your API spec
158
+ res did not satisfy it because: integerProperty should be integer
159
+
160
+ res contained: {
161
+ body: {
162
+ stringProperty: 'string',
163
+ integerProperty: 'invalid (should be an integer)'
164
+ }
165
+ }
166
+ }
167
+
168
+ The '200' response defined for endpoint 'GET /example/endpoint' in API spec: {
169
+ '200': {
170
+ description: 'Response body should be a string',
171
+ content: {
172
+ 'application/json': {
173
+ schema: {
174
+ type: 'string'
175
+ }
176
+ }
177
+ }
178
+ },
179
+ }
180
+ ```
181
+
182
+ ### In unit tests, validate objects against schemas defined in your OpenAPI spec:
183
+
184
+ #### 1. Write a test:
185
+
186
+ ```javascript
187
+ // Set up Chai
188
+ import chai from 'chai';
189
+ const expect = chai.expect;
190
+
191
+ // Import this plugin and the function you want to test
192
+ import chaiResponseValidator from '@ehuelsmann/chai-openapi-response-validator';
193
+ import { functionToTest } from 'path/to/your/code';
194
+
195
+ // Load an OpenAPI file (YAML or JSON) into this plugin
196
+ chai.use(chaiResponseValidator('path/to/openapi.yml'));
197
+
198
+ // Write your test (e.g. using Mocha)
199
+ describe('functionToTest()', () => {
200
+ it('should satisfy OpenAPI spec', async () => {
201
+ // Assert that the function returns a value satisfying a schema defined in your OpenAPI spec
202
+ expect(functionToTest()).to.satisfySchemaInApiSpec('ExampleSchemaObject');
203
+ });
204
+ });
205
+ ```
206
+
207
+ #### 2. Write an OpenAPI Spec (and save to `path/to/openapi.yml`):
208
+
209
+ ```yaml
210
+ openapi: 3.0.0
211
+ info:
212
+ title: Example API
213
+ version: 1.0.0
214
+ paths:
215
+ /example:
216
+ get:
217
+ responses:
218
+ 200:
219
+ description: Response body should be an ExampleSchemaObject
220
+ content:
221
+ application/json:
222
+ schema:
223
+ $ref: '#/components/schemas/ExampleSchemaObject'
224
+ components:
225
+ schemas:
226
+ ExampleSchemaObject:
227
+ type: object
228
+ required:
229
+ - stringProperty
230
+ - integerProperty
231
+ properties:
232
+ stringProperty:
233
+ type: string
234
+ integerProperty:
235
+ type: integer
236
+ ```
237
+
238
+ #### 3. Run your test to validate your object against your OpenAPI spec:
239
+
240
+ ##### The assertion passes if the object satisfies the schema `ExampleSchemaObject`:
241
+
242
+ ```javascript
243
+ // object includes:
244
+ {
245
+ stringProperty: 'string',
246
+ integerProperty: 123,
247
+ };
248
+ ```
249
+
250
+ ##### The assertion fails if the object does not satisfy the schema `ExampleSchemaObject`:
251
+
252
+ ```javascript
253
+ // object includes:
254
+ {
255
+ stringProperty: 123,
256
+ integerProperty: 123,
257
+ };
258
+ ```
259
+
260
+ ###### Output from test failure:
261
+
262
+ ```javascript
263
+ AssertionError: expected object to satisfy schema 'ExampleSchemaObject' defined in API spec:
264
+ object did not satisfy it because: stringProperty should be string
265
+
266
+ object was: {
267
+ {
268
+ stringProperty: 123,
269
+ integerProperty: 123
270
+ }
271
+ }
272
+ }
273
+
274
+ The 'ExampleSchemaObject' schema in API spec: {
275
+ type: 'object',
276
+ required: [
277
+ 'stringProperty'
278
+ 'integerProperty'
279
+ ],
280
+ properties: {
281
+ stringProperty: {
282
+ type: 'string'
283
+ },
284
+ integerProperty: {
285
+ type: 'integer'
286
+ }
287
+ }
288
+ }
289
+ ```
290
+
291
+ ### Loading your OpenAPI spec (3 different ways):
292
+
293
+ #### 1. From an absolute filepath ([see above](#usage))
294
+
295
+ #### 2. From an object:
296
+
297
+ ```javascript
298
+ // Set up Chai
299
+ import chai from 'chai';
300
+ const expect = chai.expect;
301
+
302
+ // Import this plugin
303
+ import chaiResponseValidator from '@ehuelsmann/chai-openapi-response-validator';
304
+
305
+ // Get an object representing your OpenAPI spec
306
+ const openApiSpec = {
307
+ openapi: '3.0.0',
308
+ info: {
309
+ title: 'Example API',
310
+ version: '0.1.0',
311
+ },
312
+ paths: {
313
+ '/example/endpoint': {
314
+ get: {
315
+ responses: {
316
+ 200: {
317
+ description: 'Response body should be a string',
318
+ content: {
319
+ 'application/json': {
320
+ schema: {
321
+ type: 'string',
322
+ },
323
+ },
324
+ },
325
+ },
326
+ },
327
+ },
328
+ },
329
+ },
330
+ };
331
+
332
+ // Load that OpenAPI object into this plugin
333
+ chai.use(chaiResponseValidator(openApiSpec));
334
+
335
+ // Write your test (e.g. using Mocha)
336
+ describe('GET /example/endpoint', () => {
337
+ it('should satisfy OpenAPI spec', async () => {
338
+ // Get an HTTP response from your server (e.g. using axios)
339
+ const res = await axios.get('http://localhost:3000/example/endpoint');
340
+
341
+ expect(res.status).to.equal(200);
342
+
343
+ // Assert that the HTTP response satisfies the OpenAPI spec
344
+ expect(res).to.satisfyApiSpec;
345
+ });
346
+ });
347
+ ```
348
+
349
+ #### 3. From a web endpoint:
350
+
351
+ ```javascript
352
+ // Set up Chai
353
+ import chai from 'chai';
354
+ const expect = chai.expect;
355
+
356
+ // Import this plugin and an HTTP client (e.g. axios)
357
+ import chaiResponseValidator from '@ehuelsmann/chai-openapi-response-validator';
358
+ import axios from 'axios';
359
+
360
+ // Write your test (e.g. using Mocha)
361
+ describe('GET /example/endpoint', () => {
362
+ // Load your OpenAPI spec from a web endpoint
363
+ before(async () => {
364
+ const response = await axios.get('url/to/openapi/spec');
365
+ const openApiSpec = response.data; // e.g. { openapi: '3.0.0', <etc> };
366
+ chai.use(chaiResponseValidator(openApiSpec));
367
+ });
368
+
369
+ it('should satisfy OpenAPI spec', async () => {
370
+ // Get an HTTP response from your server (e.g. using axios)
371
+ const res = await axios.get('http://localhost:3000/example/endpoint');
372
+
373
+ expect(res.status).to.equal(200);
374
+
375
+ // Assert that the HTTP response satisfies the OpenAPI spec
376
+ expect(res).to.satisfyApiSpec;
377
+ });
378
+ });
379
+ ```
@@ -0,0 +1,3 @@
1
+ import { OpenApiSpec } from '@ehuelsmann/openapi-validator';
2
+ export default function (chai: Chai.ChaiStatic, openApiSpec: OpenApiSpec): void;
3
+ //# sourceMappingURL=satisfyApiSpec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"satisfyApiSpec.d.ts","sourceRoot":"","sources":["../../lib/assertions/satisfyApiSpec.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,WAAW,EAEZ,MAAM,+BAA+B,CAAC;AAGvC,MAAM,CAAC,OAAO,WACZ,IAAI,EAAE,IAAI,CAAC,UAAU,EACrB,WAAW,EAAE,WAAW,GACvB,IAAI,CAuBN"}
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = default_1;
4
+ const openapi_validator_1 = require("@ehuelsmann/openapi-validator");
5
+ const utils_1 = require("../utils");
6
+ function default_1(chai, openApiSpec) {
7
+ const { Assertion } = chai;
8
+ Assertion.addProperty('satisfyApiSpec', function () {
9
+ const actualResponse = (0, openapi_validator_1.makeResponse)(this._obj); // eslint-disable-line no-underscore-dangle
10
+ const validationError = openApiSpec.validateResponse(actualResponse);
11
+ const pass = !validationError;
12
+ this.assert(pass, pass
13
+ ? ''
14
+ : getExpectedResToSatisfyApiSpecMsg(actualResponse, openApiSpec, validationError), pass
15
+ ? getExpectedResNotToSatisfyApiSpecMsg(actualResponse, openApiSpec)
16
+ : '', null);
17
+ });
18
+ }
19
+ function getExpectedResToSatisfyApiSpecMsg(actualResponse, openApiSpec, validationError) {
20
+ const hint = 'expected res to satisfy API spec';
21
+ const { status, req } = actualResponse;
22
+ const { method, path: requestPath } = req;
23
+ const unmatchedEndpoint = `${method} ${requestPath}`;
24
+ if (validationError.code === openapi_validator_1.ErrorCode.ServerNotFound) {
25
+ return (0, utils_1.joinWithNewLines)(hint, `expected res to satisfy a '${status}' response defined for endpoint '${unmatchedEndpoint}' in your API spec`, `res had request path '${requestPath}', but your API spec has no matching servers`, `Servers found in API spec: ${openApiSpec
26
+ .getServerUrls()
27
+ .join(', ')}`);
28
+ }
29
+ if (validationError.code === openapi_validator_1.ErrorCode.BasePathNotFound) {
30
+ return (0, utils_1.joinWithNewLines)(hint, `expected res to satisfy a '${status}' response defined for endpoint '${unmatchedEndpoint}' in your API spec`, `res had request path '${requestPath}', but your API spec has basePath '${openApiSpec.spec.basePath}'`);
31
+ }
32
+ if (validationError.code === openapi_validator_1.ErrorCode.PathNotFound) {
33
+ const pathNotFoundErrorMessage = (0, utils_1.joinWithNewLines)(hint, `expected res to satisfy a '${status}' response defined for endpoint '${unmatchedEndpoint}' in your API spec`, `res had request path '${requestPath}', but your API spec has no matching path`, `Paths found in API spec: ${openApiSpec.paths().join(', ')}`);
34
+ if ('didUserDefineBasePath' in openApiSpec &&
35
+ openApiSpec.didUserDefineBasePath) {
36
+ return (0, utils_1.joinWithNewLines)(pathNotFoundErrorMessage, `'${requestPath}' matches basePath \`${openApiSpec.spec.basePath}\` but no <basePath/endpointPath> combinations`);
37
+ }
38
+ if ('didUserDefineServers' in openApiSpec &&
39
+ openApiSpec.didUserDefineServers) {
40
+ return (0, utils_1.joinWithNewLines)(pathNotFoundErrorMessage, `'${requestPath}' matches servers ${(0, utils_1.stringify)(openApiSpec.getMatchingServerUrls(requestPath))} but no <server/endpointPath> combinations`);
41
+ }
42
+ return pathNotFoundErrorMessage;
43
+ }
44
+ const path = openApiSpec.findOpenApiPathMatchingRequest(req);
45
+ const endpoint = `${method} ${path}`;
46
+ if (validationError.code === openapi_validator_1.ErrorCode.MethodNotFound) {
47
+ const expectedPathItem = openApiSpec.findExpectedPathItem(req);
48
+ const expectedRequestOperations = Object.keys(expectedPathItem)
49
+ .map((operation) => operation.toUpperCase())
50
+ .join(', ');
51
+ return (0, utils_1.joinWithNewLines)(hint, `expected res to satisfy a '${status}' response defined for endpoint '${endpoint}' in your API spec`, `res had request method '${method}', but your API spec has no '${method}' operation defined for path '${path}'`, `Request operations found for path '${path}' in API spec: ${expectedRequestOperations}`);
52
+ }
53
+ if (validationError.code === openapi_validator_1.ErrorCode.StatusNotFound) {
54
+ const expectedResponseOperation =
55
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
56
+ openApiSpec.findExpectedResponseOperation(req);
57
+ const expectedResponseStatuses = Object.keys(expectedResponseOperation.responses).join(', ');
58
+ return (0, utils_1.joinWithNewLines)(hint, `expected res to satisfy a '${status}' response defined for endpoint '${endpoint}' in your API spec`, `res had status '${status}', but your API spec has no '${status}' response defined for endpoint '${endpoint}'`, `Response statuses found for endpoint '${endpoint}' in API spec: ${expectedResponseStatuses}`);
59
+ }
60
+ // validationError.code === ErrorCode.InvalidBody
61
+ const responseDefinition = openApiSpec.findExpectedResponse(actualResponse);
62
+ return (0, utils_1.joinWithNewLines)(hint, `expected res to satisfy the '${status}' response defined for endpoint '${endpoint}' in your API spec`, `res did not satisfy it because: ${validationError}`, `res contained: ${actualResponse.toString()}`, `The '${status}' response defined for endpoint '${endpoint}' in API spec: ${(0, utils_1.stringify)(responseDefinition)}`);
63
+ }
64
+ function getExpectedResNotToSatisfyApiSpecMsg(actualResponse, openApiSpec) {
65
+ const { status, req } = actualResponse;
66
+ const responseDefinition = openApiSpec.findExpectedResponse(actualResponse);
67
+ const endpoint = `${req.method} ${openApiSpec.findOpenApiPathMatchingRequest(req)}`;
68
+ return (0, utils_1.joinWithNewLines)(`expected res not to satisfy API spec`, `expected res not to satisfy the '${status}' response defined for endpoint '${endpoint}' in your API spec`, `res contained: ${actualResponse.toString()}`, `The '${status}' response defined for endpoint '${endpoint}' in API spec: ${(0, utils_1.stringify)(responseDefinition)}`);
69
+ }
70
+ //# sourceMappingURL=satisfyApiSpec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"satisfyApiSpec.js","sourceRoot":"","sources":["../../lib/assertions/satisfyApiSpec.ts"],"names":[],"mappings":";;AAWA,4BA0BC;AArCD,qEAQuC;AACvC,oCAAuD;AAEvD,mBACE,IAAqB,EACrB,WAAwB;IAExB,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IAE3B,SAAS,CAAC,WAAW,CAAC,gBAAgB,EAAE;QACtC,MAAM,cAAc,GAAG,IAAA,gCAAY,EAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,2CAA2C;QAE3F,MAAM,eAAe,GAAG,WAAW,CAAC,gBAAgB,CAAC,cAAc,CAAC,CAAC;QACrE,MAAM,IAAI,GAAG,CA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oCAAoC,MAAM,oCAAoC,QAAQ,oBAAoB,EAC1G,kBAAkB,cAAc,CAAC,QAAQ,EAAE,EAAE,EAC7C,QAAQ,MAAM,oCAAoC,QAAQ,kBAAkB,IAAA,iBAAS,EACnF,kBAAkB,CACnB,EAAE,CACJ,CAAC;AACJ,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { OpenApiSpec } from '@ehuelsmann/openapi-validator';
2
+ export default function (chai: Chai.ChaiStatic, openApiSpec: OpenApiSpec): void;
3
+ //# sourceMappingURL=satisfySchemaInApiSpec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"satisfySchemaInApiSpec.d.ts","sourceRoot":"","sources":["../../lib/assertions/satisfySchemaInApiSpec.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAA2B,MAAM,+BAA+B,CAAC;AAG1F,MAAM,CAAC,OAAO,WACZ,IAAI,EAAE,IAAI,CAAC,UAAU,EACrB,WAAW,EAAE,WAAW,GACvB,IAAI,CAmCN"}
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = default_1;
4
+ const utils_1 = require("../utils");
5
+ function default_1(chai, openApiSpec) {
6
+ const { Assertion, AssertionError } = chai;
7
+ Assertion.addMethod('satisfySchemaInApiSpec', function (schemaName) {
8
+ const actualObject = this._obj; // eslint-disable-line no-underscore-dangle
9
+ const schema = openApiSpec.getSchemaObject(schemaName);
10
+ if (!schema) {
11
+ // alert users they are misusing this assertion
12
+ // eslint-disable-next-line @typescript-eslint/no-throw-literal
13
+ throw new AssertionError('The argument to satisfySchemaInApiSpec must match a schema in your API spec');
14
+ }
15
+ const validationError = openApiSpec.validateObject(actualObject, schema);
16
+ const pass = !validationError;
17
+ this.assert(pass, pass
18
+ ? ''
19
+ : getExpectReceivedToSatisfySchemaInApiSpecMsg(actualObject, schemaName, schema, validationError), getExpectReceivedNotToSatisfySchemaInApiSpecMsg(actualObject, schemaName, schema), null);
20
+ });
21
+ }
22
+ function getExpectReceivedToSatisfySchemaInApiSpecMsg(received, schemaName, schema, validationError) {
23
+ return (0, utils_1.joinWithNewLines)(`expected object to satisfy the '${schemaName}' schema defined in your API spec`, `object did not satisfy it because: ${validationError}`, `object was: ${(0, utils_1.stringify)(received)}`, `The '${schemaName}' schema in API spec: ${(0, utils_1.stringify)(schema)}`);
24
+ }
25
+ function getExpectReceivedNotToSatisfySchemaInApiSpecMsg(received, schemaName, schema) {
26
+ return (0, utils_1.joinWithNewLines)(`expected object not to satisfy the '${schemaName}' schema defined in your API spec`, `object was: ${(0, utils_1.stringify)(received)}`, `The '${schemaName}' schema in API spec: ${(0, utils_1.stringify)(schema)}`);
27
+ }
28
+ //# sourceMappingURL=satisfySchemaInApiSpec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"satisfySchemaInApiSpec.js","sourceRoot":"","sources":["../../lib/assertions/satisfySchemaInApiSpec.ts"],"names":[],"mappings":";;AAGA,4BAsCC;AAxCD,oCAAuD;AAEvD,mBACE,IAAqB,EACrB,WAAwB;IAExB,MAAM,EAAE,SAAS,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;IAE3C,SAAS,CAAC,SAAS,CAAC,wBAAwB,EAAE,UAAU,UAAU;QAChE,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,2CAA2C;QAE3E,MAAM,MAAM,GAAG,WAAW,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC;QACvD,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,+CAA+C;YAC/C,+DAA+D;YAC/D,MAAM,IAAI,cAAc,CACtB,6EAA6E,CAC9E,CAAC;QACJ,CAAC;QAED,MAAM,eAAe,GAAG,WAAW,CAAC,cAAc,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;QACzE,MAAM,IAAI,GAAG,CAAC,eAAe,CAAC;QAC9B,IAAI,CAAC,MAAM,CACT,IAAI,EACJ,IAAI;YACF,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,4CAA4C,CAC1C,YAAY,EACZ,UAAU,EACV,MAAM,EACN,eAAe,CAChB,EACL,+CAA+C,CAC7C,YAAY,EACZ,UAAU,EACV,MAAM,CACP,EACD,IAAI,CACL,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,4CAA4C,CACnD,QAAiB,EACjB,UAAkB,EAClB,MAAc,EACd,eAAgC;IAEhC,OAAO,IAAA,wBAAgB,EACrB,mCAAmC,UAAU,mCAAmC,EAChF,sCAAsC,eAAe,EAAE,EACvD,eAAe,IAAA,iBAAS,EAAC,QAAQ,CAAC,EAAE,EACpC,QAAQ,UAAU,yBAAyB,IAAA,iBAAS,EAAC,MAAM,CAAC,EAAE,CAC/D,CAAC;AACJ,CAAC;AAED,SAAS,+CAA+C,CACtD,QAAiB,EACjB,UAAkB,EAClB,MAAc;IAEd,OAAO,IAAA,wBAAgB,EACrB,uCAAuC,UAAU,mCAAmC,EACpF,eAAe,IAAA,iBAAS,EAAC,QAAQ,CAAC,EAAE,EACpC,QAAQ,UAAU,yBAAyB,IAAA,iBAAS,EAAC,MAAM,CAAC,EAAE,CAC/D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { OpenAPISpecObject } from '@ehuelsmann/openapi-validator';
2
+ declare global {
3
+ namespace Chai {
4
+ interface Assertion {
5
+ /**
6
+ * Check the HTTP response object satisfies a response defined in your OpenAPI spec.
7
+ * [See usage example](https://github.com/openapi-library/OpenAPIValidators/tree/master/packages/chai-openapi-response-validator#in-api-tests-validate-the-status-and-body-of-http-responses-against-your-openapi-spec)
8
+ */
9
+ satisfyApiSpec: Assertion;
10
+ /**
11
+ * Check the object satisfies a schema defined in your OpenAPI spec.
12
+ * [See usage example](https://github.com/openapi-library/OpenAPIValidators/tree/master/packages/chai-openapi-response-validator#in-unit-tests-validate-objects-against-schemas-defined-in-your-openapi-spec)
13
+ */
14
+ satisfySchemaInApiSpec(schemaName: string): Assertion;
15
+ }
16
+ }
17
+ }
18
+ export default function (filepathOrObject: string | OpenAPISpecObject): Chai.ChaiPlugin;
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAI/E,OAAO,CAAC,MAAM,CAAC;IAEb,UAAU,IAAI,CAAC;QACb,UAAU,SAAS;YACjB;;;eAGG;YACH,cAAc,EAAE,SAAS,CAAC;YAC1B;;;eAGG;YACH,sBAAsB,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;SACvD;KACF;CACF;AAED,MAAM,CAAC,OAAO,WACZ,gBAAgB,EAAE,MAAM,GAAG,iBAAiB,GAC3C,IAAI,CAAC,UAAU,CAMjB"}
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = default_1;
7
+ const openapi_validator_1 = require("@ehuelsmann/openapi-validator");
8
+ const satisfyApiSpec_1 = __importDefault(require("./assertions/satisfyApiSpec"));
9
+ const satisfySchemaInApiSpec_1 = __importDefault(require("./assertions/satisfySchemaInApiSpec"));
10
+ function default_1(filepathOrObject) {
11
+ const openApiSpec = (0, openapi_validator_1.makeApiSpec)(filepathOrObject);
12
+ return function (chai) {
13
+ (0, satisfyApiSpec_1.default)(chai, openApiSpec);
14
+ (0, satisfySchemaInApiSpec_1.default)(chai, openApiSpec);
15
+ };
16
+ }
17
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":";;;;;AAsBA,4BAQC;AA9BD,qEAA+E;AAC/E,iFAAyD;AACzD,iGAAyE;AAoBzE,mBACE,gBAA4C;IAE5C,MAAM,WAAW,GAAG,IAAA,+BAAW,EAAC,gBAAgB,CAAC,CAAC;IAClD,OAAO,UAAU,IAAI;QACnB,IAAA,wBAAc,EAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QAClC,IAAA,gCAAsB,EAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,3 @@
1
+ export declare const stringify: (obj: unknown) => string;
2
+ export declare const joinWithNewLines: (...lines: string[]) => string;
3
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../lib/utils.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,SAAS,GAAI,KAAK,OAAO,KAAG,MACS,CAAC;AAEnD,eAAO,MAAM,gBAAgB,GAAI,GAAG,OAAO,MAAM,EAAE,KAAG,MAClC,CAAC"}
package/dist/utils.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.joinWithNewLines = exports.stringify = void 0;
4
+ const util_1 = require("util");
5
+ const stringify = (obj) => (0, util_1.inspect)(obj, { showHidden: false, depth: null });
6
+ exports.stringify = stringify;
7
+ const joinWithNewLines = (...lines) => lines.join('\n\n');
8
+ exports.joinWithNewLines = joinWithNewLines;
9
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../lib/utils.ts"],"names":[],"mappings":";;;AAAA,+BAA+B;AAExB,MAAM,SAAS,GAAG,CAAC,GAAY,EAAU,EAAE,CAChD,IAAA,cAAO,EAAC,GAAG,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AADtC,QAAA,SAAS,aAC6B;AAE5C,MAAM,gBAAgB,GAAG,CAAC,GAAG,KAAe,EAAU,EAAE,CAC7D,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AADR,QAAA,gBAAgB,oBACR"}
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@ehuelsmann/chai-openapi-response-validator",
3
+ "version": "0.15.0",
4
+ "description": "Use Chai to assert that HTTP responses satisfy an OpenAPI spec",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "clean": "rimraf dist",
9
+ "clean:openapi-validator": "cd ../openapi-validator && yarn clean",
10
+ "build:openapi-validator": "cd ../openapi-validator && yarn build",
11
+ "format": "prettier --write ../../ --ignore-path ../../.prettierignore",
12
+ "lint": "tsc --noEmit --project tsconfig.eslint.json && eslint .",
13
+ "lint:fix": "yarn lint --fix",
14
+ "build": "tsc",
15
+ "test": "ts-mocha --extension ts --recursive",
16
+ "test:watch": "yarn test --watch",
17
+ "test:coverage": "yarn clean && yarn clean:openapi-validator && yarn build && yarn build:openapi-validator && nyc yarn test && nyc report --reporter=lcov && nyc check-coverage",
18
+ "test:coverage:browse": "yarn test:coverage; open ../coverage/lcov-report/index.html",
19
+ "test:ci": "yarn format && yarn lint && yarn test:coverage",
20
+ "prepack": "yarn build"
21
+ },
22
+ "repository": "https://github.com/openapi-library/OpenAPIValidators/tree/master/packages/chai-openapi-response-validator",
23
+ "author": "OpenApiChai <openapichai@gmail.com>",
24
+ "contributors": [
25
+ "Jonny Spruce <jspruce94@gmail.com>",
26
+ "rwalle61 <richard.lh.waller@gmail.com>"
27
+ ],
28
+ "license": "MIT",
29
+ "keywords": [
30
+ "chai",
31
+ "chai-plugin",
32
+ "http",
33
+ "response",
34
+ "openapi",
35
+ "validate"
36
+ ],
37
+ "bugs": {
38
+ "url": "https://github.com/openapi-library/OpenAPIValidators/issues"
39
+ },
40
+ "homepage": "https://github.com/openapi-library/OpenAPIValidators/tree/master/packages/chai-openapi-response-validator#readme",
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "files": [
45
+ "dist"
46
+ ],
47
+ "devDependencies": {
48
+ "@types/chai": "^4.2.15",
49
+ "@types/mocha": "^8.2.1",
50
+ "@types/request-promise": "^4.1.48",
51
+ "@types/supertest": "^7.2.0",
52
+ "axios": "^1.15.0",
53
+ "chai": "^6.2.2",
54
+ "chai-http": "^5.1.2",
55
+ "eslint": "^7.11.0",
56
+ "eslint-plugin-chai-friendly": "^1.2.0",
57
+ "eslint-plugin-import": "^2.22.1",
58
+ "eslint-plugin-mocha": "^8.0.0",
59
+ "express": "^5.2.1",
60
+ "fs-extra": "^9.0.1",
61
+ "mocha": "^8.2.0",
62
+ "nyc": "15.1.0",
63
+ "request": "^2.88.2",
64
+ "request-promise": "^4.2.6",
65
+ "rimraf": "^3.0.2",
66
+ "supertest": "^7.2.2",
67
+ "ts-mocha": "^8.0.0"
68
+ },
69
+ "dependencies": {
70
+ "@ehuelsmann/openapi-validator": "^0.15.0"
71
+ }
72
+ }