Mocking GraphQL, MockList genertes only two items

2019-05-15 04:03发布

问题:

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.