diff --git a/src/__tests__/lib.test.ts b/src/__tests__/lib.test.ts index bcb51bf..d69e777 100644 --- a/src/__tests__/lib.test.ts +++ b/src/__tests__/lib.test.ts @@ -3,7 +3,7 @@ import { GraphQLError } from "graphql"; import schema from "./schema"; import schemaAST from "./schema-ast.json"; -const seed = 'seed'; +const seed = "seed"; describe("Automocking", () => { describe("Guardrails", () => { @@ -1134,6 +1134,25 @@ describe("Automocking", () => { }); }); + describe("mocking aliases", () => { + test("can handle aliases", () => { + const testQuery = /* GraphQL */ ` + { + int1: returnInt + int2: returnInt + int3: returnInt + } + `; + const mocks = { + int1: 1, + int2: 2, + int3: 3, + }; + const resp: any = ergonomock(schema, testQuery, { mocks }); + expect(resp.data).toEqual(mocks); + }); + }); + describe("default mock resolvers", () => { test("can mock partiallly resolved objects", () => { const testQuery = /* GraphQL */ ` diff --git a/src/mock.ts b/src/mock.ts index 6819710..1de4a9d 100644 --- a/src/mock.ts +++ b/src/mock.ts @@ -94,15 +94,18 @@ export function ergonomock( // 2. if the nullableType is a list, recurse // 3. if there's no mock defined, use the default mocks for this type return (root, args, context, info) => { + const fieldNameWithAlias = + info.fieldNodes.find((node) => node.kind === "Field")?.alias?.value ?? fieldName; + // nullability doesn't matter for the purpose of mocking. const fieldType = getNullableType(type) as GraphQLNullableType; - if (root && fieldName && typeof root[fieldName] !== "undefined") { - const mock = root[fieldName]; + if (root && fieldNameWithAlias && typeof root[fieldNameWithAlias] !== "undefined") { + const mock = root[fieldNameWithAlias]; if (typeof mock === "function") { return mock(root, args, context, info); } - return root[fieldName]; + return mock; } // Lists