Skip to content

Pass index value as parameter to List mocks #4498

Open
@dalevfenton

Description

@dalevfenton

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: '[email protected]',
        type: 'email',
      }
    ]
  }
}
 */

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions