- Setting up another custom graphql express app from scratch. It’s possible to add custom middleware using
graphql-middleware
. This lets us write functions that can called before every resolver. Example boilerplate for what custom graphql middleware looks like:
export const log = async (
resolver: any,
parent: any,
args: any,
context: any,
info: any
) => {
if (!parent) {
console.log("Start Logging");
}
const result = await resolver(parent, args, context, info);
console.log("finished call to resolver");
return result;
};
-
Learning how to write unit test for graphql query resolvers
- write a
testGraphQLQuery
wrapper function, takes theschema
,source
andvariableValues
:
import { graphql, GraphQLSchema } from "graphql"; import { Maybe } from "graphql/jsutils/Maybe"; interface Options { schema: GraphQLSchema; source: string; variableValues?: Maybe<{ [key: string]: any }>; } export const testGraphQLQuery = async ({ schema, source, variableValues, }: Options) => { return graphql({ schema, source, variableValues, }); };
- This can then be use in a jest test suite. Using the
makeExecutableSchema
function we can pass in our real type definitions and resolvers as theschema
parameter. - we can pass in a real stringified Graphql query for the
source
parameter - we can pass in an arbitary argument the graphql query accepts as the
variableValues
parameter. Example code:
import typeDefs from "./typeDefs"; import resolvers from "./resolvers"; import { makeExecutableSchema } from "graphql-tools"; import faker from "faker"; import { testGraphQLQuery } from "./testGraphQLquery"; import { addMockFunctionsToSchema } from "apollo-server-express"; describe("test getting a user", () => { const GetUser = ` query GetUser($id: ID!){ getUser(id: $id){ id username email } } `; it("get the desired user", async () => { const schema = makeExecutableSchema({ typeDefs, resolvers }); const userId = faker.random.alphaNumeric(20); const username = faker.internet.userName(); const email = faker.internet.email(); const mocks = { User: () => ({ id: userId, username, email, }), }; addMockFunctionsToSchema({ schema, mocks }); const queryResponse = await testGraphQLQuery({ schema, source: GetUser, variableValues: { id: faker.random.alphaNumeric(20) }, }); const result = queryResponse.data ? queryResponse.data.getUser : null; expect(result).toEqual({ id: userId, username, email, }); }); });
- write a