diff --git a/src/__tests__/lib.test.ts b/src/__tests__/lib.test.ts index f8271d2..e9e780e 100644 --- a/src/__tests__/lib.test.ts +++ b/src/__tests__/lib.test.ts @@ -6,10 +6,31 @@ import schema from "./schema"; describe("Automocking", () => { describe("Guardrails", () => { - test.todo("it throws without a schema"); - test.todo("it throws without a valid schema"); - test.todo("it throws without a query"); - test.todo("it throws without a valid query"); + test("it throws without a schema", () => { + expect(() => { + (ergonomock as any)(); + }).toThrowError("Ergonomock requires a valid GraphQL schema"); + }); + test("it throws without a valid schema", () => { + expect(() => { + (ergonomock as any)("foo", "bar"); + }).toThrowError("Ergonomock requires a valid GraphQL schema"); + }); + test("it throws without a query", () => { + expect(() => { + (ergonomock as any)(schema); + }).toThrowError("Ergonomock requires a GraphQL query, either as a string or DocumentNode."); + }); + test("it throws without a parseable query", () => { + expect(() => { + (ergonomock as any)(schema, "asdasd"); + }).toThrowError("Syntax Error: Unexpected Name"); + }); + test("it throws without a valid query", () => { + expect(() => { + (ergonomock as any)(schema, "query { fooBar }"); + }).toThrowError('Cannot query field "fooBar" on type "RootQuery".'); + }); }); describe("No provided mocks", () => { @@ -670,7 +691,9 @@ describe("Automocking", () => { returnEnum returnBirdsAndBees { __typename - returnInt + ... on Flying { + returnInt + } ... on Bird { returnString } @@ -933,7 +956,9 @@ describe("Automocking", () => { { returnBirdsAndBees { __typename - id + ... on Flying { + id + } } returnString } diff --git a/src/mock.ts b/src/mock.ts index 25404d5..404e936 100644 --- a/src/mock.ts +++ b/src/mock.ts @@ -14,7 +14,9 @@ import { GraphQLList, GraphQLEnumType, isObjectType, - DocumentNode + DocumentNode, + isSchema, + validate } from "graphql"; import random from "./utils/random"; @@ -39,9 +41,24 @@ export function ergonomock( mocks?: ErgonoMockShape, mockSeed?: string ) { - random.seed(mockSeed); + // Guard rails for schema & query + if (!schema || !isSchema(schema)) { + throw new Error("Ergonomock requires a valid GraphQL schema."); + } + + if (!query) { + throw new Error("Ergonomock requires a GraphQL query, either as a string or DocumentNode."); + } + const document = typeof query === "string" ? parse(query) : query; + const errors = validate(schema, document); + if (errors.length) { + throw errors[0]; + } + + random.seed(mockSeed); + const mockResolverFunction = function( type: GraphQLType, typeName?: string, // TODO: get rid of this?