Skip to content

Commit

Permalink
Merge pull request #5 from CruGlobal/support-aliases
Browse files Browse the repository at this point in the history
Support aliases
  • Loading branch information
canac authored Nov 15, 2024
2 parents 0447b60 + 4c68520 commit 6477ca6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
21 changes: 20 additions & 1 deletion src/__tests__/lib.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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 */ `
Expand Down
9 changes: 6 additions & 3 deletions src/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 6477ca6

Please sign in to comment.