-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgraphql-service.test.ts
More file actions
82 lines (69 loc) · 2.69 KB
/
Copy pathgraphql-service.test.ts
File metadata and controls
82 lines (69 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { describe, it, expect } from 'vitest';
import type { IGraphQLService, GraphQLRequest, GraphQLResponse } from './graphql-service';
describe('GraphQL Service Contract', () => {
it('should allow a minimal IGraphQLService implementation with required methods', () => {
const service: IGraphQLService = {
execute: async (_request, _context?) => ({ data: null }),
};
expect(typeof service.execute).toBe('function');
});
it('should allow a full implementation with optional methods', () => {
const service: IGraphQLService = {
execute: async () => ({ data: null }),
handleRequest: async (_request) => new Response('OK'),
getSchema: () => 'type Query { hello: String }',
};
expect(service.handleRequest).toBeDefined();
expect(service.getSchema).toBeDefined();
});
it('should execute a GraphQL query', async () => {
const service: IGraphQLService = {
execute: async (request): Promise<GraphQLResponse> => {
if (request.query.includes('hello')) {
return { data: { hello: 'world' } };
}
return { data: null, errors: [{ message: 'Unknown query' }] };
},
};
const result = await service.execute({ query: '{ hello }' });
expect(result.data).toEqual({ hello: 'world' });
expect(result.errors).toBeUndefined();
});
it('should return errors for invalid queries', async () => {
const service: IGraphQLService = {
execute: async (): Promise<GraphQLResponse> => ({
data: null,
errors: [{
message: 'Cannot query field "invalid"',
locations: [{ line: 1, column: 3 }],
}],
}),
};
const result = await service.execute({ query: '{ invalid }' });
expect(result.errors).toHaveLength(1);
expect(result.errors![0].message).toContain('invalid');
});
it('should support variables in queries', async () => {
const service: IGraphQLService = {
execute: async (request: GraphQLRequest): Promise<GraphQLResponse> => {
const id = request.variables?.id;
return { data: { user: { id, name: 'Alice' } } };
},
};
const result = await service.execute({
query: 'query GetUser($id: ID!) { user(id: $id) { id name } }',
operationName: 'GetUser',
variables: { id: 'u1' },
});
expect(result.data?.user).toEqual({ id: 'u1', name: 'Alice' });
});
it('should return SDL schema', () => {
const service: IGraphQLService = {
execute: async () => ({ data: null }),
getSchema: () => 'type Query { users: [User] }\ntype User { id: ID! name: String }',
};
const schema = service.getSchema!();
expect(schema).toContain('type Query');
expect(schema).toContain('User');
});
});