Mocking GraphQL,MockList仅生成数组中的两个项目 [英] Mocking GraphQL, MockList genertes only two items in the array

查看:91
本文介绍了Mocking GraphQL,MockList仅生成数组中的两个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的GraphQL模拟服务器中生成10个项目的列表,如下所示:

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?

关于, 莫斯塔法(Mostafa)

Regards, Mostafa

推荐答案

在您的代码中,您正在为UsedCar类型定义一个模拟解析器.您没有发布您的typeDefs或解析器,但是我猜您对UsedCar的类型定义包括两个字段(价格和年份)...而不是包含这两个字段的完整对象数组.但是,这就是您要告诉您的模拟功能.

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.

如果您有一个获取UsedCar类型数组的查询,为了获取10个该类型的模拟对象,您将必须模拟该查询.因此,假设您有一个类似getUsedCars的查询,那么您真正想要的是:

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),
  })
}

:如果您仅模拟类型,则模式中解析为该类型数组的任何地方默认都会返回两个模拟对象,这就是为什么看到的是两个而不是十个.

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.

这篇关于Mocking GraphQL,MockList仅生成数组中的两个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆