Mocking GraphQL, MockList genertes only two items in the array

感情迁移 提交于 2019-12-07 13:53:19

问题


I am trying to generate a list of 10 items in my GraphQL mock server like this:

import { makeExecutableSchema, addMockFunctionsToSchema, MockList } from 'graphql-tools';
import casual from 'casual';
import typeDefs from './schema.graphql';

export const schema = makeExecutableSchema({ typeDefs });

const mocks = {
  File: () => ({
    path: casual.random_element([
      '/assets/images/cars/1.JPG',
      '/assets/images/cars/2.JPG',
      '/assets/images/cars/3.JPG',
      '/assets/images/cars/4.JPG',
      '/assets/images/cars/5.JPG',
      '/assets/images/cars/6.JPG',
      '/assets/images/cars/7.JPG',
    ]),
  }),
  UsedCar: () =>
    new MockList(10, () => ({
      price: casual.integer(10000, 99999999),
      year: casual.integer(1990, 2017),
    })),
};

// This function call adds the mocks to your schema!
addMockFunctionsToSchema({ schema, mocks });

But I always get two used cars I don't know why. Can anyone help?

Regards, Mostafa


回答1:


In your code, you are defining a mock resolver for your UsedCar type. You didn't post your typeDefs or resolvers, but I'm guessing your type definition for UsedCar includes the two fields (price and year)... not a whole array of objects with those two fields. However, that is what you are telling the mock function you have.

If you have a query that fetches an array of UsedCar types, in order to get 10 mocked objects of that type, you will have to mock both the query and the type. So, assuming you have a query like getUsedCars, what you really want is:

mocks: {
  Query: () => ({
    getUsedCars: () => new MockList(10)
  }),
  UsedCar: () => ({
    price: casual.integer(10000, 99999999),
    year: casual.integer(1990, 2017),
  })
}

Edit: If you only mock the type, anywhere in the schema that resolves to an array of that type will return two mocked objects by default, which is why you were seeing two instead of ten.



来源:https://stackoverflow.com/questions/45000522/mocking-graphql-mocklist-genertes-only-two-items-in-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!