// 第一步:引入所依賴的庫函數
const { makeExecutableSchema, addMockFunctionsToSchema } = require('graphql-tools'); const { graphql } = require('graphql');
// 第二步:定義GraphQL Schemaui
const schemaString = ` type User { id: ID, name: String, age: Int, address: String } type Query { user: User } `;
// 樣例數據code
const user = { id: 1, name: 'zhang' };
// 第三步:定義Resolver對象
const resolvers = { Query: { user: () => user } };
// 第四步:調用makeExecutableSchema函數生成Schema對象get
const schema = makeExecutableSchema({ typeDefs: schemaString, resolvers });
// 第五步:也是重要的一步,調用addMockFunctionsToSchema函數mock Schemagraphql
addMockFunctionsToSchema({ schema, mocks: { Int: () => 6, Float: () => 22.1, String: () => 'Hello' } });
// 第六步:也是最後一步,查詢並驗證結果io
const query = ` query tasksForUser { user { id, name, age, address } } `; graphql(schema, query).then(result => console.log('Got result', result));
// 參考資料網址: https://www.apollographql.com/docs/graphql-tools/mocking/console