-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.ts
124 lines (102 loc) · 2.78 KB
/
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import {
assert,
assertEquals,
assertRejects,
} from "https://deno.land/[email protected]/assert/mod.ts";
import { carbonFootprint } from "./mod.ts";
const json = (data: unknown) =>
new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" },
});
const getBaseUrl = (server: Deno.HttpServer<Deno.NetAddr>): string =>
`http://${server.addr.hostname}:${server.addr.port}`;
Deno.test("makes distance requests", async () => {
const server = Deno.serve((req) => {
const url = new URL(req.url);
assertEquals(url.pathname, "/v1/footprint");
assertEquals(url.searchParams.get("activity"), "10");
assertEquals(url.searchParams.get("activityType"), "miles");
assertEquals(url.searchParams.get("mode"), "taxi");
assertEquals(url.searchParams.get("country"), "usa");
assert(!url.searchParams.has("fuelType"));
return json({ carbonFootprint: "1.23" });
});
assertEquals(
await carbonFootprint({
baseUrl: getBaseUrl(server),
country: "USA",
distance: {
amount: 10,
unit: "miles",
mode: "taxi",
},
}),
1.23,
);
await server.shutdown();
});
Deno.test("makes fuel requests", async () => {
const server = Deno.serve((req) => {
const url = new URL(req.url);
assertEquals(url.pathname, "/v1/footprint");
assertEquals(url.searchParams.get("activity"), "456");
assertEquals(url.searchParams.get("activityType"), "fuel");
assertEquals(url.searchParams.get("fuelType"), "jetFuel");
assertEquals(url.searchParams.get("country"), "gbr");
assert(!url.searchParams.get("mode"));
return json({ carbonFootprint: "1.23" });
});
assertEquals(
await carbonFootprint({
baseUrl: getBaseUrl(server),
country: "GBR",
fuel: {
amount: 456,
unit: "gallons",
type: "jetFuel",
},
}),
1.23,
);
await server.shutdown();
});
Deno.test("token", async () => {
const server = Deno.serve((req) => {
const url = new URL(req.url);
assertEquals(url.searchParams.get("appTkn"), "foobar");
return json({ carbonFootprint: "1.23" });
});
assertEquals(
await carbonFootprint({
token: "foobar",
baseUrl: getBaseUrl(server),
country: "GBR",
fuel: {
amount: 456,
unit: "gallons",
type: "jetFuel",
},
}),
1.23,
);
await server.shutdown();
});
Deno.test("errors from API", async () => {
const server = Deno.serve(() => json({ errorMessage: "foobar" }));
await assertRejects(
() => (
carbonFootprint({
baseUrl: getBaseUrl(server),
country: "USA",
distance: {
amount: 10,
unit: "miles",
mode: "taxi",
},
})
),
Error,
"foobar",
);
await server.shutdown();
});