|
| 1 | +const { deepStrictEqual, strictEqual } = require('assert') |
| 2 | +const setup = require('./setup') |
| 3 | +const formatError = (error) => { |
| 4 | + const { message, code, fieldName, context } = error?.originalError?.originalError || error?.originalError || error |
| 5 | + return { message, code, fieldName, context } |
| 6 | +} |
| 7 | + |
| 8 | +describe('@constraint Int in ARGUMENT_DEFINITION', function () { |
| 9 | + describe('#max', function () { |
| 10 | + const query = /* GraphQL */` |
| 11 | + query ($size: size_Int_max_3) { |
| 12 | + books(size: $size) { |
| 13 | + title |
| 14 | + } |
| 15 | + } |
| 16 | + ` |
| 17 | + |
| 18 | + before(async function () { |
| 19 | + this.typeDefs = /* GraphQL */` |
| 20 | + type Query { |
| 21 | + books (size: Int @constraint(max: 3)): [Book] |
| 22 | + } |
| 23 | + type Book { |
| 24 | + title: String |
| 25 | + } |
| 26 | + ` |
| 27 | + |
| 28 | + this.request = await setup(this.typeDefs) |
| 29 | + }) |
| 30 | + |
| 31 | + it('should pass', async function () { |
| 32 | + const { body, statusCode } = await this.request |
| 33 | + .post('/graphql') |
| 34 | + .set('Accept', 'application/json') |
| 35 | + .send({ query, variables: { size: 2 } }) |
| 36 | + |
| 37 | + strictEqual(statusCode, 200) |
| 38 | + deepStrictEqual(body, { data: { books: null } }) |
| 39 | + }) |
| 40 | + |
| 41 | + it('should fail', async function () { |
| 42 | + const { body, statusCode } = await this.request |
| 43 | + .post('/graphql') |
| 44 | + .set('Accept', 'application/json') |
| 45 | + .send({ query, variables: { size: 100 } }) |
| 46 | + |
| 47 | + strictEqual(statusCode, 400) |
| 48 | + strictEqual(body.errors[0].message, |
| 49 | + 'Variable "$size" got invalid value 100; Expected type "size_Int_max_3". Must be no greater than 3') |
| 50 | + }) |
| 51 | + |
| 52 | + it('should throw custom error', async function () { |
| 53 | + const request = await setup(this.typeDefs, formatError) |
| 54 | + const { body, statusCode } = await request |
| 55 | + .post('/graphql') |
| 56 | + .set('Accept', 'application/json') |
| 57 | + .send({ query, variables: { size: 100 } }) |
| 58 | + |
| 59 | + strictEqual(statusCode, 400) |
| 60 | + deepStrictEqual(body.errors[0], { |
| 61 | + message: 'Must be no greater than 3', |
| 62 | + code: 'ERR_GRAPHQL_CONSTRAINT_VALIDATION', |
| 63 | + fieldName: 'size', |
| 64 | + context: [{ arg: 'max', value: 3 }] |
| 65 | + }) |
| 66 | + }) |
| 67 | + }) |
| 68 | +}) |
0 commit comments