前端技术之:如何Mock GraphQL接口数据

发布于 2019-11-12  约 3 分钟

// 第一步:引入所依赖的库

const { makeExecutableSchema, addMockFunctionsToSchema } = require('graphql-tools');
const { graphql } = require('graphql');

// 第二步:定义GraphQL Schema

const schemaString = `
  type User {
    id: ID,
    name: String,
    age: Int,
    address: String
  }
  type Query {
    user: User
  }
`;

// 样例数据

const user = { id: 1, name: 'zhang' };

// 第三步:定义Resolver

const resolvers = {
  Query: {
    user: () => user
  }
};

// 第四步:调用makeExecutableSchema函数生成Schema对象

const schema = makeExecutableSchema({ typeDefs: schemaString, resolvers });

// 第五步:也是重要的一步,调用addMockFunctionsToSchema函数mock Schema

addMockFunctionsToSchema({
  schema,
  mocks: {
    Int: () => 6,
    Float: () => 22.1,
    String: () => 'Hello'
  }
});

// 第六步:也是最后一步,查询并验证结果

const query = `
query tasksForUser {
  user {
    id,
    name,
    age,
    address
  }
}
`;
graphql(schema, query).then(result => console.log('Got result', result));

// 参考资料网址: https://www.apollographql.com...

阅读 205发布于 2019-11-12

推荐阅读
目录