Back to results for “GraphQL”
Node.js › GraphQL

How would you write automated tests for GraphQL resolvers in Node.js, testing them independently of the full HTTP/schema execution layer?

Advanced

Answer

Resolvers are typically plain functions (or objects containing functions), letting them be unit tested directly by calling them with mock arguments and a mock context, without needing to spin up a full Apollo Server instance or send actual GraphQL query strings over HTTP -- for more complete integration-level testing that verifies the schema itself is correctly wired up, a library like apollo-server-testing (or executing queries against a test server instance in-memory) can run full GraphQL queries against the actual schema and resolvers together.
test('user resolver returns the requested user', async () => {
  const mockContext = { dataSources: { userAPI: { getUser: jest.fn().mockResolvedValue({ id: '1', name: 'Alice' }) } } };
  const result = await resolvers.Query.user(null, { id: '1' }, mockContext);
  expect(result.name).toBe('Alice');
});
Real-world example A team unit tests each resolver function in isolation with mocked data sources for fast, focused tests, while maintaining a smaller suite of integration tests that execute complete GraphQL queries against a real in-memory test server instance to verify the schema and resolvers are correctly wired together end-to-end.

Common follow-ups: What's the tradeoff between fast, isolated resolver unit tests and slower, more complete integration tests executing real GraphQL queries?;How would you mock a DataLoader instance specifically for testing a resolver that depends on it?