Complete the code to define a basic resolver function that returns a fixed string.
const resolvers = { Query: { hello: () => [1] } };The resolver must return a string value. Using quotes returns the string correctly.
Complete the resolver to accept arguments and return the name argument.
const resolvers = { Query: { greet: (_, [1]) => name } };The resolver receives arguments as the second parameter. Destructuring { name } extracts the name argument.
Fix the error in the resolver that tries to return a user by id from a data source.
const resolvers = { Query: { user: (_, { id }, [1]) => [1].dataSources.userAPI.getUserById(id) } };The third parameter is the context, which contains dataSources. Using 'context' allows access to userAPI.
Fill both blanks to write a test that mocks the data source and checks the resolver output.
test('user resolver returns user data', async () => { const mockUser = { id: '1', name: 'Alice' }; const context = { dataSources: { userAPI: { getUserById: jest.fn().mockResolvedValue([1]) } } } }; const result = await resolvers.Query.user(null, { id: '1' }, [2]); expect(result).toEqual(mockUser); });
The mockResolvedValue should return the mockUser object. The context parameter must be passed to the resolver.
Fill all three blanks to write a test that verifies the resolver throws an error when user is not found.
test('user resolver throws error if user not found', async () => { const context = { dataSources: { userAPI: { getUserById: jest.fn().mockResolvedValue([1]) } } } }; await expect(resolvers.Query.user(null, { id: '2' }, [2])).rejects.toThrow([3]); });
The mock returns null to simulate no user found. The context is passed to the resolver. The test expects an error with message 'User not found'.