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

37次阅读

共计 762 个字符,预计需要花费 2 分钟才能阅读完成。

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

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…

正文完
 0