Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass index value as parameter to List mocks #4498

Open
dalevfenton opened this issue Jun 1, 2022 · 0 comments
Open

Pass index value as parameter to List mocks #4498

dalevfenton opened this issue Jun 1, 2022 · 0 comments

Comments

@dalevfenton
Copy link

Is your feature request related to a problem? Please describe.
When mocking a field that is an array of a given type, I can mock that type, but if I want to have a list that is consistent then it's a ton of work to write a mock for that type.

If MockList passed the index of the array it is currently building it would be easier to create a list where a certain set of values is populated for each index consistently.

Same issue for a normal mock that is used in a list field.

Describe the solution you'd like

  • for MockList: pass the value of i to this.wrappedFunction() in https://github.com/ardatan/graphql-tools/blob/master/packages/mock/src/MockList.ts#L53;
  • for regular mocks: for a List type mock, pass the index of the current item in the list to the mock resolver

Describe alternatives you've considered
Implementing mocks that contain their own auto-incrementing count.

Additional context
example of the idea here

const typeDefs = `
  type Contact {
    phone: String
    email: String
    type: String!
  }
  type User {
    id: Id!
    name: String!
    contacts: Contact[]
  }
  type Query {
    me: User!
  }
`;

const contactBuilder = (index: number) => {
  return index % 2 === 0
    ? {
        phone: casual.phone,
        type: 'phone',
      }
    : {
        email: casual.email,
        type: 'email',
      };
};

const mocks = {
  Contact: contactBuilder,
  User: () => ({
    name: casual.name,
    contacts: [...new Array(2)], // or MockList(2, contactBuilder)
  }),
};

const server = mockServer(typeDefs, mocks);

const query = `
  query me {
    me {
      __typename
      id
      name
      contacts {
        __typename
        phone
        email
        type
      }
    }
  }
`;

const res = await server.query(query, {});

/** res
{
  me: {
    __typename: 'User',
    id: '437d3d3f-2c0a-4e25-b76b-d7afb572b901',
    name: 'Alberto',
    contacts: [
      {
        __typename: 'Contact',
        phone: '982-790-2592',
        type: 'phone',
      },
      {
        __typename: 'Contact',
        email: 'Josue.Hessel@claire.us',
        type: 'email',
      }
    ]
  }
}
 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant