Mocking GraphQL with Apollo Server
Thanks to mocking, UI development can begin before the backend is fully functional. The UI can be tested without having to wait for lengthy database operations or maintaining a full-fledged GraphQL server.
There are a number of community-built tools, such as graphql-tools, graphql-faker, and Apollo Server's in-built mocking feature, that make it simple to simulate user interactions with a GraphQL API by simulating their queries and schema.
In order to test our resolvers before actually implementing them, let's use Apollo Server's mocking feature to simulate GraphQL requests.
Head to the src/index.ts
file and simply add mocks: true
to Apollo Server, as follows:
const server : ApolloServer = new ApolloServer({schema , mocks: true});
The mocking functionality built into Apollo Server is simplistic. A value of the same type as the associated field is simply returned based on the type definitions. Please enter the following query into Apollo Studio:
query {
findUsers(searchQuery:"ahmed"){
id name email postsCount
}
findPostsByUserId(userId:"10"){
id text postBy { id name } commentsCount
latestComment { id comment }
datetime
}
}
This shows that the default behavior for queries that are supposed to return a list of values is to return only two values, and that the value Hello World is returned for every field that accepts strings. This gives the results the right general shape, but it's not at all realistic. The good news is that we can use tools like casual, a fake data generator for JavaScript, to return more realistic and random values from GraphQL queries before implementing the necessary resolvers, in conjunction with Apollo Server.
Since the frontend developer can interact with the GraphQL API and retrieve the generated data without waiting for the backend developer to implement the resolvers, the frontend developer can begin building the frontend immediately. One problem that may arise is that our mocked API does not properly link entries that should be linked in a real-world scenario.
In the next article, we'll see how to configure CORS in our backend to allow our frontend development server (Angular CLI) to connect with our API without getting blocked by the Same Origin Policy in web browsers.
-
Date: