Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

AK DevCraft
AK DevCraftSubscriber

Posted on • Edited on

Setup GraphQL Mock Server

Introduction

Using a mock server for backend APIs streamlines frontend development by eliminating backend dependencies. While it’s relatively simple for RESTful APIs, setting up a GraphQL mock server can be more tedious. This tutorial walks you through creating a GraphQL mock server for your JavaScript application. A mock server is invaluable for local development, allowing seamless testing when the backend is unavailable or during E2E tests.

Prerequisites

Before proceeding, ensure the following tools are installed on your system:

  • Node.js
  • npm/yarn/pnpm

Step-by-step Guide

1. Install Dependencies

Begin by installing the necessary dependencies with npm or yarn:

npminstall--save-dev graphql graphql-tag graphql-tools @apollo/server node-fetch
Enter fullscreen modeExit fullscreen mode

2. Setup Project Structure

Set up your project directory as follows:

/graphql-mock-server  |-- localSchema.ts  |-- schema.graphql  |-- server.ts
Enter fullscreen modeExit fullscreen mode

3. Local Schema

Define your local schema in localSchema.ts. This schema will override remote schema definitions for specific queries or mutations. Provide resolvers to return predefined mock data.

// filepath: /graphql-mock-server/localSchema.tsimport{makeExecutableSchema}from'@graphql-tool/schema'import{gql}from'graphql-tag'consttypeDefs=gql`  type Query {    myQuery: String  }`;constresolvers={Query:{myQuery:()=>'This is mock data'},};exportconstlocalSchema=makeExecutableSchema({typeDefs,resolvers});
Enter fullscreen modeExit fullscreen mode

4. Remote Schema

The remote schema is loaded from the local fileschema.graphql. This file should include the schema definition, which can be exported from your GraphQL playground.

// filepath: /graphql-mock-server/schema.graphqltypeQuery{myQuery:String}
Enter fullscreen modeExit fullscreen mode

5. Mock Server Implementation

The mock server stitches the local and remote schemas, giving precedence to the local schema-specified queries or mutations.

// filepath: /graphql-mock-server/server.tsimport{ApolloServer}from'@apollo/server';import{startStandaloneServer}from'@apollo/server/standalone';import{stitchSchema}from'@graphql-tools/stitch';import{loadSchemaSync}from'@graphql-tools/load';import{GraphQLFileLoader}from'@graphql-tools/graphql-file-loader';import{localSchema}from'./localSchema';import{wrapSchema}from'@graphql-tools/wrap';import{print}from'graphql';importfetchfrom'node-fetch';asyncfunctionstartServer(){constremoteSchema=loadSchemaSync('graphql-mock-server/schema.graphql',{loaders:[newGraphQLFileLoader()],});constexecutableRemoteSchema=wrapSchema({schema:remoteSchema,executor:async({document,variables})=>{constquery=print(document);constfetchResult=awaitfetch('https://graphql.server.com/graphql',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({query,variables}),},);returnfetchResult.json();},});constschema=stitchSchema({subschema:[{schema:executableRemoteSchema},{schema:localSchema},merge:{myQuery:{//override the Query/Mutation hereselectionSet:'{ __typename }',resolve:(parent,args,context,info)=>{returnlocalSchema.getQueryType()?.getFields().myQuery.resolve(parent,args,context,info);},},},},},],});constserver=ApolloServer({schema});const{url}=awaitstartStandaloneServer(server,{listen:{port:4000},});console.log(`🚀 Server ready at${url}`);}startServer();
Enter fullscreen modeExit fullscreen mode

If you have reached here, then I made a satisfactory effort to keep you reading. Please be kind enough to leave any comments or share corrections.

My Other Blogs:

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full-Stack Software Engineer, creating digital solutions across various platforms. Programming and software engineering are essential part of my life just like air 😎
  • Work
    Software Engineer
  • Joined

More fromAK DevCraft

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp