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

查看:20
本文介绍了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?

问候,莫斯塔法

推荐答案

在您的代码中,您正在为 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天全站免登陆