Skip to content

Commit

Permalink
Add support for aliases
Browse files Browse the repository at this point in the history
  • Loading branch information
canac committed Nov 15, 2024
1 parent 338120e commit 4c68520
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
19 changes: 19 additions & 0 deletions src/__tests__/lib.test.ts
Original file line number Diff line number Diff line change
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 4c68520

Please sign in to comment.