-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock.test.ts
104 lines (89 loc) · 2.52 KB
/
mock.test.ts
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import fs from "fs";
import type { IncomingMessage } from "http";
import http from "http";
import type { AddressInfo } from "net";
import type { Server } from "http";
import { addMocksToSchema } from "@graphql-tools/mock";
import { makeExecutableSchema } from "@graphql-tools/schema";
import connect from "connect";
import { graphqlHTTP } from "express-graphql";
import { createClient } from "../dist";
import { Chance } from "chance";
declare global {
var __TEST_TRANSITLAND_SERVER__: Server;
}
const transitlandSchemaString = fs.readFileSync(
require
// change this to .resolve('@ioki/transitland-gql-client')
.resolve("../dist/index.js")
.replace("index.js", "schema.graphql"),
"utf8"
);
const transitlandSchema = makeExecutableSchema({
typeDefs: transitlandSchemaString,
});
// initializing chance (random generator) with a seed so we get deterministic values
const chance = new Chance(109);
const schemaWithMocks = addMocksToSchema({
schema: transitlandSchema,
mocks: {
Query: () => {
return {
/**
* Returning an empty array determines how many mocked objects will be returned.
* Without this the mock returns 2 elements for iterables.
*/
routes: () => [...Array(5)],
};
},
Route: () => {
// hint: use
return {
route_type: chance.pickone([0, 1, 2, 3]),
route_id: chance.string({ length: 12 }),
};
},
},
});
const graphqlServer = graphqlHTTP({
schema: schemaWithMocks,
graphiql: false,
});
const transitlandServer = () => {
if (!global.__TEST_TRANSITLAND_SERVER__) {
const app = connect();
app.use("/graphql", (req, res) => {
void graphqlServer(req as IncomingMessage & { url: string }, res);
});
global.__TEST_TRANSITLAND_SERVER__ = http.createServer(app).listen(0);
}
return global.__TEST_TRANSITLAND_SERVER__;
};
beforeAll(() => {
transitlandServer();
});
afterAll(async () => {
await new Promise<void>((resolve) =>
transitlandServer().close(() => resolve())
);
});
test("run something against the mocked server", async () => {
const transitlandClient = createClient({
apiKey: "unused",
url: `http://localhost:${
(transitlandServer().address() as AddressInfo).port
}/graphql`,
});
const result = await transitlandClient.query({
routes: {
route_type: true,
route_id: true,
},
feeds: {
onestop_id: true,
},
});
expect(result.routes).toHaveLength(5);
expect(result.feeds).toHaveLength(2);
expect(result).toMatchSnapshot();
});