Skip to content

Commit

Permalink
Make enum mocking deterministic
Browse files Browse the repository at this point in the history
  • Loading branch information
canac committed Oct 30, 2024
1 parent 785b8b0 commit 7cb19b0
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 8 deletions.
9 changes: 8 additions & 1 deletion src/__tests__/lib.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { GraphQLError } from "graphql";
import schema from "./schema";
import schemaAST from "./schema-ast.json";

const seed = 'seed';

describe("Automocking", () => {
describe("Guardrails", () => {
test("it throws without a valid schema", () => {
Expand Down Expand Up @@ -89,10 +91,15 @@ describe("Automocking", () => {
returnEnum
}
`;
const resp: any = ergonomock(schema, testQuery);
const resp: any = ergonomock(schema, testQuery, { seed });
expect(resp.data).toMatchObject({
returnEnum: expect.toBeOneOf(["A", "B", "C"]),
});

for (let i = 0; i < 10; ++i) {
const resp2 = ergonomock(schema, testQuery, { seed });
expect(resp).toEqual(resp2);
}
});

test("can automock unions", () => {
Expand Down
5 changes: 2 additions & 3 deletions src/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import {
buildASTSchema,
} from "graphql";
import random from "./utils/random";
import getRandomElement from "./utils/getRandomElement";
import forEachFieldInQuery from "./utils/forEachFieldInQuery";

const defaultMockMap: Map<string, GraphQLFieldResolver<any, any>> = new Map();
Expand Down Expand Up @@ -117,7 +116,7 @@ export function ergonomock(
if (fieldType instanceof GraphQLUnionType || fieldType instanceof GraphQLInterfaceType) {
let implementationType;
const possibleTypes = schema.getPossibleTypes(fieldType);
implementationType = getRandomElement(possibleTypes);
implementationType = random.item(possibleTypes);
return Object.assign(
{ __typename: implementationType },
mockResolverFunction(implementationType)(root, args, context, info)
Expand All @@ -130,7 +129,7 @@ export function ergonomock(

// Default mock for enums
if (fieldType instanceof GraphQLEnumType) {
return getRandomElement(fieldType.getValues()).value;
return random.item(fieldType.getValues()).value;
}

// Automock object types
Expand Down
4 changes: 0 additions & 4 deletions src/utils/getRandomElement.ts

This file was deleted.

2 changes: 2 additions & 0 deletions src/utils/random.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,8 @@ const random = {
// max is exclusive, min is inclusive
float: (max: number = 100, min: number = 1) => rng() * (max - min) + min,

item: <T>(array: readonly T[]): T => array[random.integer(array.length, 0)],

// max and min are inclusive
list: (maxLength: number = 4, minLength: number = 1) => [
...Array(random.integer(maxLength + 1, minLength))
Expand Down

0 comments on commit 7cb19b0

Please sign in to comment.