Building a Mock Server for Frontend Development: A Practical Guide Using @graphql-tools/mock and Faker

  • apollo
    apollo
  • graphql
    graphql
  • expressjs
    expressjs
  • typescript
    typescript
  • jest
    jest
Published on 2024/12/30

Introduction

In frontend development, you often want to move ahead with UI and feature implementation before the backend is complete. However, when the backend APIs are not yet available, fetching and manipulating data can become difficult. This is where a mock server becomes useful.

In this article, we will create mock data for a GraphQL-based backend and use @graphql-tools/mock and Faker to spin up a mock server that helps you proceed smoothly with frontend development. By doing this, you can efficiently continue frontend work while waiting for the backend database to be ready.

Along with the steps to build a mock server, we will also show examples of how to use it in a real development environment, so try it out yourself.

For the schema definition, we will use the one created in the following blog post.

https://shinagawa-web.com/en/blogs/typescript-apollo-server-express-mongodb-guide

Goal for This Article

We will build a GraphQL server using Express and Apollo Server, and configure it so that when a query is executed, it returns dummy data as the response.

Below is the response when running a query in Apollo Playground. Fields like id and title are set, but these values are automatically generated by Faker.

Image from Gyazo

Project Setup

Create a new project for the mock server and install the required packages.

mkdir express-mongodb-graphql-with-typescript
cd express-mongodb-graphql-with-typescript
npm init -y

Installing Packages

After pasting the following content into package.json:

  "dependencies": {
    "@apollo/server": "^4.11.3",
    "cors": "^2.8.5",
    "dotenv": "^16.4.7",
    "express": "^4.21.2",
    "graphql": "^16.10.0",
    "graphql-tag": "^2.12.6"
  },
  "devDependencies": {
    "@types/cors": "^2.8.17",
    "@types/express": "4.17.2",
    "@types/express-serve-static-core": "^4.17.21",
    "@types/graphql": "^14.5.0",
    "@types/node": "^22.10.5",
    "ts-node-dev": "^2.0.0",
    "typescript": "^5.7.3"
  }

install all packages at once.

npm install

Defining the GraphQL Schema

Assuming we are building a TODO app, we will prepare the following fields.

src/graphql/schema.ts
import { gql } from 'graphql-tag';

export const typeDefs = gql`
  scalar Date

  type Todo {
    id: ID!
    title: String!
    isCompleted: Boolean!
    createdAt: Date!
    updatedAt: Date
  }

  type Query {
    todos: [Todo!]
    todo(id: ID!): Todo
  }
`;

We will also define a custom scalar.

src/graphql/scalar.ts
import { GraphQLScalarType, Kind } from 'graphql';

export const DateScalar = new GraphQLScalarType({
  name: 'Date',
  description: 'Date custom scalar type',
  serialize(value) {
    if (value instanceof Date) {
      return value.toISOString();
    }
    throw Error('GraphQL Date Scalar serializer expected a `Date` object');
  },
  parseValue(value) {
    if (typeof value === 'number') {
      return new Date(value);
    }
    throw new Error('GraphQL Date Scalar parser expected a `number`');
  },
  parseLiteral(ast) {
    if (ast.kind === Kind.INT) {
      return new Date(parseInt(ast.value, 10));
    }
    return null;
  },
});

Creating Mock Data

We will configure mock data generation based on the schema above.

Installing Packages

npm install @graphql-tools/mock @faker-js/faker
  • @graphql-tools/mock: Generates mock data based on a GraphQL schema.
  • faker: A library for generating random data (names, dates, IDs, etc.).

https://the-guild.dev/graphql/tools

https://fakerjs.dev/

Mock Data

We define the todo and todos queries.

For todos, we configure it to return 10 items in the response.

src/mocks/mock.ts
import { faker } from '@faker-js/faker';

export const mocks = {
  Todo: () => ({
    title: faker.lorem.sentence(),
    isCompleted: faker.datatype.boolean(),
    createdAt: faker.date.past().toISOString(),
    updatedAt: faker.datatype.boolean() ? faker.date.recent().toISOString() : null,
  }),
  Query: () => ({
    todos: () => Array.from({ length: 10 }),
    todo: () => ({}),
  }),
};

Starting the Mock Server

Finally, we will use these definitions to start Apollo Server.

The PORT number is set to 8080.

src/mockServer.ts
import express from 'express'
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import cors from 'cors';

import { addMocksToSchema } from '@graphql-tools/mock';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { typeDefs } from './graphql/schema';
import { mocks } from './mocks/mock';

const schema = makeExecutableSchema({ typeDefs });

const mockedSchema = addMocksToSchema({
  schema,
  mocks,
});

const app = express();
const PORT = 8080;

const server = new ApolloServer({
  schema: mockedSchema,
});

async function startServer() {
  await server.start();
  app.use(
    '/graphql',
    cors(),
    express.json(),
    expressMiddleware(server)
  );

  app.listen(PORT, () =>
    console.log(`Mock GraphQL server running at http://localhost:${PORT}/graphql`)
  );
}

startServer();

Verifying Operation

Start the server with the following command:

npx ts-node-dev src/mockServer.ts

When you execute the todos query, you will get a response like the one below.

Image from Gyazo

You can also confirm that the todo query returns a response.

Image from Gyazo

By combining a schema definition with a few packages, you can spin up a mock server.

If you keep it running locally, the frontend can access GraphQL and you can proceed with implementation without waiting for backend development.

Conclusion

In this article, we introduced how to set up a mock server using GraphQL and Express to accelerate frontend development. By leveraging a mock server, you can implement the frontend before the backend is finished and greatly improve development efficiency.

We also used @faker-js/faker to randomly generate mock data and simulate realistic data, providing a more practical development environment. With this kind of mock server, the frontend team can continue development without waiting for the backend implementation, enabling smoother collaboration.

When you want to run frontend and backend development in parallel, a mock server is an extremely useful tool. Be sure to try incorporating it into your own projects.

Thank you for reading to the end. I hope using a mock server helps make your development a bit more efficient.

Xでシェア
Facebookでシェア
LinkedInでシェア

Questions about this article 📝

If you have any questions or feedback about the content, please feel free to contact us.
Go to inquiry form