Search code examples
javascriptmockinggraphqlaws-appsyncresolver

AppSync GraphQL Mocking Resolver Map Not Generating Unique Items


My mock is not generating unique data for each item, rather each items have the same field value.

Option 1: (ideal approach, incorrect results)

The AppSync schema holds an items field of [Model], if I put the Model resolver by itself, all the Model in the items list have the same value.

const mocks = {
  ModelModelConnection: () => ({
    items: () => new MockList(5),
  }),
  Model: () => ({
    id: casual.uuid,
    name: casual.title,
  }),
};

results in... Results


Option 2: (alternative method, correct results)

const mocks = {
  ModelModelConnection: () => ({
    items: () => new MockList(5, () => ({
      id: casual.uuid,
      name: casual.title,
    })),
  }),
};

Results


I want to go with Option 1, but I can't seem to get unique items to be mocked. Been scratching my head on this one. Thanks in advance!


Solution

  • As shown in the docs, if you want to generate a different value each time a field's resolver is fired, the mock resolver should be a function, not a value. So instead of:

    Model: () => ({
      id: casual.uuid,
      name: casual.title,
    }),
    

    you should do:

    Model: () => ({
      id: () => casual.uuid,
      name: () => casual.title,
    }),
    

    This causes id and name to be called each time the field is resolved.