ardatan / ardatan/graphql-tools

Pass index value as parameter to List mocks

Open
#4,498 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
TypeScript
Stars
5.4k
Forks
830
Avg merge
10h 59m
Merged PRs (30d)
45

Description

**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',
}
]
}
}
*/
```

Contributor guide

Open the contributing guide

Research direction

Start in packages/mock/src/MockList.ts at line 53 and trace how list-type mocks invoke their wrapped functions. Then locate the regular mock resolver path for list fields. Done means both MockList and regular list mocks receive the current item index, with the behavior covered by the relevant mock tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
testing
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.