Skip to content

Commit

Permalink
feat: guardrails for ergonomock()
Browse files Browse the repository at this point in the history
  • Loading branch information
joual committed Mar 23, 2020
1 parent 3547a78 commit fe2f213
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 8 deletions.
37 changes: 31 additions & 6 deletions src/__tests__/lib.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down Expand Up @@ -670,7 +691,9 @@ describe("Automocking", () => {
returnEnum
returnBirdsAndBees {
__typename
returnInt
... on Flying {
returnInt
}
... on Bird {
returnString
}
Expand Down Expand Up @@ -933,7 +956,9 @@ describe("Automocking", () => {
{
returnBirdsAndBees {
__typename
id
... on Flying {
id
}
}
returnString
}
Expand Down
21 changes: 19 additions & 2 deletions src/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ import {
GraphQLList,
GraphQLEnumType,
isObjectType,
DocumentNode
DocumentNode,
isSchema,
validate
} from "graphql";

import random from "./utils/random";
Expand All @@ -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?
Expand Down

0 comments on commit fe2f213

Please sign in to comment.