-
Notifications
You must be signed in to change notification settings - Fork 594
/
main_test.ts
1246 lines (1112 loc) · 35.6 KB
/
main_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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ServerContext, STATUS_CODE } from "../server.ts";
import {
assert,
assertEquals,
assertMatch,
assertStringIncludes,
delay,
join,
puppeteer,
retry,
} from "./deps.ts";
import manifest from "./fixture/fresh.gen.ts";
import config from "./fixture/fresh.config.ts";
import { BUILD_ID } from "../src/server/build_id.ts";
import {
assertSelector,
assertTextMany,
parseHtml,
startFreshServer,
waitForText,
withFakeServe,
withPageName,
} from "./test_utils.ts";
const ctx = await ServerContext.fromManifest(manifest, config);
const handler = ctx.handler();
Deno.test("/ page prerender", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/"));
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
assertEquals(resp.headers.get("server"), "fresh test server");
const body = await resp.text();
assertStringIncludes(body, `<html lang="en">`);
assertStringIncludes(body, "test.js");
assertStringIncludes(body, "<p>Hello!</p>");
assertStringIncludes(body, "<p>Viewing JIT render.</p>");
assertStringIncludes(body, `>{"v":[[{"message":"Hello!"}],[]]}</script>`);
assertStringIncludes(
body,
'<meta name="description" content="Hello world!"/>',
);
assertStringIncludes(
body,
'<meta name="generator" content="The freshest framework!"/>',
);
assert(
!body.includes("specialTag"),
`Expected actual: "${body}" to not contain: "specialTag"`,
);
assertStringIncludes(body, `<link rel="modulepreload"`);
});
Deno.test("/greet/[name] page prerender", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/bar"));
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
const body = await resp.text();
assertStringIncludes(body, "<div>Hello bar</div>");
});
Deno.test("/api/head_override - HEAD", async () => {
const req = new Request("https://fresh.deno.dev/api/head_override", {
method: "HEAD",
});
const resp = await handler(req);
assert(resp);
assertEquals(resp.status, STATUS_CODE.NoContent);
assertEquals(resp.body, null);
assertEquals(
resp.headers.get("content-type"),
"text/html; charset=utf-8",
);
});
Deno.test("/api/get_only - HEAD fallback", async () => {
const req = new Request("https://fresh.deno.dev/api/get_only", {
method: "HEAD",
});
const resp = await handler(req);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
assertEquals(resp.body, null);
assertEquals(
resp.headers.get("content-type"),
"application/json; charset=utf-8",
);
});
Deno.test("/intercept - GET html", async () => {
const req = new Request("https://fresh.deno.dev/intercept", {
headers: { "accept": "text/html" },
});
const resp = await handler(req);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertStringIncludes(body, "<div>This is HTML</div>");
});
Deno.test("/intercept - GET text", async () => {
const req = new Request("https://fresh.deno.dev/intercept", {
headers: { "accept": "text/plain" },
});
const resp = await handler(req);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertEquals(body, "This is plain text");
});
Deno.test("/intercept - POST", async () => {
const req = new Request("https://fresh.deno.dev/intercept", {
method: "POST",
});
const resp = await handler(req);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertEquals(body, "POST response");
});
Deno.test("/intercept - DELETE", async () => {
const req = new Request("https://fresh.deno.dev/intercept", {
method: "DELETE",
});
const resp = await handler(req);
assert(resp);
assertEquals(resp.status, STATUS_CODE.MethodNotAllowed);
});
Deno.test("/intercept_args - GET html", async () => {
const req = new Request("https://fresh.deno.dev/intercept_args", {
headers: { "accept": "text/html" },
});
const resp = await handler(req);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertStringIncludes(body, "<div>intercepted</div>");
});
Deno.test("/status_overwrite", async () => {
const req = new Request("https://fresh.deno.dev/status_overwrite", {
headers: { "accept": "text/html" },
});
const resp = await handler(req);
assert(resp);
assertEquals(resp.status, STATUS_CODE.Unauthorized);
assertEquals(resp.headers.get("x-some-header"), "foo");
const body = await resp.text();
assertStringIncludes(body, "<div>This is HTML</div>");
});
Deno.test("/api/get_only - NOTAMETHOD", async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/api/get_only", {
method: "NOTAMETHOD",
}),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.MethodNotAllowed);
});
Deno.test("/api/xyz not found", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/api/xyz"));
assert(resp);
assertEquals(resp.status, STATUS_CODE.NotFound);
const body = await resp.text();
assertStringIncludes(body, "404 not found: /api/xyz");
});
Deno.test("/static page prerender", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/static"));
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
const body = await resp.text();
assert(!body.includes(`main.js`));
assert(!body.includes(`island-test.js`));
assertStringIncludes(body, "<p>This is a static page.</p>");
assertStringIncludes(body, `src="/image.png?__frsh_c=`);
assert(!body.includes("__FRSH_ISLAND_PROPS"));
});
Deno.test("/books/:id page - /books/123", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/books/123"));
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
const body = await resp.text();
assertStringIncludes(body, "<div>Book 123</div>");
});
Deno.test("/books/:id page - /books/abc", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/books/abc"));
assert(resp);
assertEquals(resp.status, STATUS_CODE.NotFound);
});
Deno.test("/i18n{/:lang}?/lang page - /i18n/lang", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/i18n/lang"));
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
const body = await resp.text();
assertStringIncludes(body, "<div>Hello</div>");
});
Deno.test("/i18n{/:lang}?/lang page - /i18n/en/lang", async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/i18n/en/lang"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
const body = await resp.text();
assertStringIncludes(body, "<div>Hello en</div>");
});
Deno.test("redirect /pages/fresh/ to /pages/fresh", async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/pages/fresh/"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.TemporaryRedirect);
assertEquals(
resp.headers.get("location"),
"/pages/fresh",
);
});
Deno.test("redirect /pages/////fresh///// to /pages/fresh", async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/pages/////fresh/////"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.TemporaryRedirect);
assertEquals(
resp.headers.get("location"),
"/pages/fresh",
);
});
Deno.test("redirect /pages/////fresh/ to /pages/fresh", async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/pages/////fresh/"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.TemporaryRedirect);
assertEquals(
resp.headers.get("location"),
"/pages/fresh",
);
});
Deno.test("no redirect for /pages/////fresh", async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/pages/////fresh"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.NotFound);
});
Deno.test("no open redirect when passing double slashes", async () => {
const resp = await handler(
new Request("https://fresh.deno.dev//evil.com/"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.TemporaryRedirect);
assertEquals(resp.headers.get("location"), "/evil.com");
});
Deno.test("/failure", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/failure"));
assert(resp);
assertEquals(resp.status, STATUS_CODE.InternalServerError);
const body = await resp.text();
assert(body.includes("500 internal error: it errored!"));
assertStringIncludes(
body,
`<meta name="generator" content="The freshest framework!"/>`,
);
});
Deno.test("/foo/:path*", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/foo/bar/baz"));
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assert(body.includes("bar/baz"));
});
Deno.test("static files in custom directory", async () => {
const newCtx = await ServerContext.fromManifest(manifest, {
...config,
staticDir: "./custom_static",
});
const newRouter = (req: Request) => {
return newCtx.handler()(req, {
remoteAddr: {
transport: "tcp",
hostname: "127.0.0.1",
port: 80,
},
});
};
const resp = await newRouter(
new Request("https://fresh.deno.dev/custom.txt"),
);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assert(body.startsWith("dir"));
});
Deno.test("static file - by file path", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/foo.txt"));
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assert(body.startsWith("bar"));
const etag = resp.headers.get("etag");
assert(etag);
// The etag is not weak, because this did not go through content encoding, so
// this is not a real server.
assert(!etag.startsWith("W/"), "etag should be weak");
assertEquals(resp.headers.get("content-type"), "text/plain; charset=UTF-8");
const resp2 = await handler(
new Request("https://fresh.deno.dev/foo.txt", {
headers: {
"if-none-match": etag,
},
}),
);
assertEquals(resp2.status, STATUS_CODE.NotModified);
assertEquals(resp2.headers.get("etag"), etag);
assertEquals(resp2.headers.get("content-type"), "text/plain; charset=UTF-8");
const resp3 = await handler(
new Request("https://fresh.deno.dev/foo.txt", {
headers: {
"if-none-match": `W/${etag}`,
},
}),
);
assertEquals(resp3.status, STATUS_CODE.NotModified);
assertEquals(resp3.headers.get("etag"), etag);
assertEquals(resp3.headers.get("content-type"), "text/plain; charset=UTF-8");
});
Deno.test("static file - spaces or other characters in name", async () => {
const res = await handler(new Request("https://fresh.deno.dev/foo bar.txt"));
assertEquals(await res.text(), "it works");
const res2 = await handler(
new Request("https://fresh.deno.dev/foo (bar).txt"),
);
assertEquals(await res2.text(), "it works");
});
Deno.test("HEAD request", async () => {
// Static file
const resp = await handler(
new Request("https://fresh.deno.dev/foo.txt", {
method: "HEAD",
}),
);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertEquals(body, "");
// route
const resp2 = await handler(
new Request("https://fresh.deno.dev/books/123", {
method: "HEAD",
}),
);
assert(resp2);
assertEquals(resp2.status, STATUS_CODE.OK);
const body2 = await resp2.text();
assertEquals(body2, "");
});
Deno.test("static file - by 'hashed' path", async () => {
// Check that the file path have the BUILD_ID
const resp = await handler(
new Request("https://fresh.deno.dev/assetsCaching"),
);
const body = await resp.text();
const imgFilePath = body.match(/img id="img-with-hashing" src="(.*?)"/)?.[1];
assert(imgFilePath);
assert(imgFilePath.includes(`?__frsh_c=${BUILD_ID}`));
// check the static file is served correctly under its cacheable route
const resp2 = await handler(
new Request(`https://fresh.deno.dev${imgFilePath}`),
);
const _ = await resp2.text();
assertEquals(resp2.status, STATUS_CODE.OK);
assertEquals(
resp2.headers.get("cache-control"),
"public, max-age=31536000, immutable",
);
const resp3 = await handler(
new Request(`https://fresh.deno.dev${imgFilePath}`, {
headers: {
"if-none-match": resp2.headers.get("etag")!,
},
}),
);
assertEquals(resp3.status, STATUS_CODE.NotModified);
// ensure asset hook is not applied on file explicitly excluded with attribute
const imgFilePathWithNoCache = body.match(
/img id="img-without-hashing" src="(.*?)"/,
)?.[1];
assert(imgFilePathWithNoCache);
assert(
!imgFilePathWithNoCache.includes(BUILD_ID),
"img-without-hashing",
);
// ensure asset hook is applied on img within an island
const imgInIsland = body.match(/img id="img-in-island" src="(.*?)"/)?.[1];
assert(imgInIsland);
assert(imgInIsland.includes(BUILD_ID), "img-in-island");
// verify that the asset hook is applied to the srcset
const imgInIslandSrcSet = body.match(/srcset="(.*?)"/)?.[1];
assert(imgInIslandSrcSet);
assert(
imgInIslandSrcSet.includes(BUILD_ID),
"img-in-island-srcset",
);
// verify that the asset hook is not applied to img outside reference out of the static folder
const imgMissing = body.match(/img id="img-missing" src="(.*?)"/)?.[1];
assert(imgMissing);
assert(
!imgMissing.includes(BUILD_ID),
"Applying hash on unknown asset",
);
});
Deno.test("/params/:path*", async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/params/bar/baz"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertEquals(body, "bar/baz");
});
Deno.test("/connInfo", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/connInfo"));
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertEquals(body, "localhost");
});
Deno.test("state in page props", async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/state-in-props"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
const body = await resp.text();
assertStringIncludes(
body,
'<meta name="generator" content="The freshest framework!"/>',
);
assertStringIncludes(body, "specialTag");
assertStringIncludes(body, "LOOK, I AM SET FROM MIDDLEWARE");
});
Deno.test({
name: "/middleware - root",
fn: async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/middleware_root"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertStringIncludes(body, "root_mw");
assert(!body.includes("layer1_mw"));
},
});
Deno.test({
name: "/middleware - mixedHandler(cors)",
fn: async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/middleware_root", {
method: "OPTIONS",
}),
);
assert(resp);
// test cors handler
assertEquals(resp.status, STATUS_CODE.NoContent);
},
});
Deno.test({
name: "/middleware - mixedHandler(log)",
fn: async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/middleware_root"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
// test log handler
const latency = resp.headers.get("latency");
assert(latency);
assert(+latency >= 0, `latency=${latency}ms `);
},
});
Deno.test({
name: "/middleware - layer 2 middleware",
fn: async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/layeredMdw/layer2/abc"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertStringIncludes(body, "root_mw");
assertStringIncludes(body, "layer1_mw");
assertStringIncludes(body, "layer2_mw");
// layered 2 should not run layer 3 middleware
assert(!body.includes("layer3_mw"));
const resp1 = await handler(
new Request("https://fresh.deno.dev/layeredMdw/layer2-no-mw/without_mw"),
);
assert(resp1);
assertEquals(resp1.status, STATUS_CODE.OK);
const body1 = await resp1.text();
assertStringIncludes(body1, "root_mw");
assertStringIncludes(body1, "layer1_mw");
// layered 2 should not run layer 2 or 3 middleware
assert(!body1.includes("layer2_mw"));
assert(!body1.includes("layer3_mw"));
},
});
Deno.test({
name: "/middleware - layer 2 middleware at index",
fn: async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/layeredMdw/layer2"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertStringIncludes(body, "root_mw");
assertStringIncludes(body, "layer1_mw");
assertStringIncludes(body, "layer2_mw");
// layered 2 should not run layer 3 middleware
assert(!body.includes("layer3_mw"));
const resp1 = await handler(
new Request("https://fresh.deno.dev/layeredMdw/layer2-no-mw/without_mw"),
);
assert(resp1);
assertEquals(resp1.status, STATUS_CODE.OK);
const body1 = await resp1.text();
assertStringIncludes(body1, "root_mw");
assertStringIncludes(body1, "layer1_mw");
// layered 2 should not run layer 2 or 3 middleware
assert(!body1.includes("layer2_mw"));
assert(!body1.includes("layer3_mw"));
},
});
Deno.test({
name: "/middleware - layer 3 middleware",
fn: async () => {
// layered 3 should contain layer 3 middleware data
const resp = await handler(
new Request("https://fresh.deno.dev/layeredMdw/layer2/layer3/abc"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertStringIncludes(body, "root_mw");
assertStringIncludes(body, "layer1_mw");
assertStringIncludes(body, "layer3_mw");
assertEquals(resp.headers.get("layer3"), "fresh test server layer3");
// the below ensure that the middlewware are applied in the correct order.
// i.e response header set from layer3 middleware is overwritten
// by the response header in layer 0
assertEquals(resp.headers.get("server"), "fresh test server");
},
});
Deno.test({
name: "/middleware - should pass state through all middlewares",
fn: async () => {
const resp = await handler(
new Request("https://fresh.deno.dev/state-middleware/foo"),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
const doc = parseHtml(body);
assertEquals(JSON.parse(doc.querySelector("pre")!.textContent!), {
handler1: "it works",
handler2: "it works",
handler3: "it works",
});
},
});
Deno.test({
name: "/middleware - middlewareParams",
fn: async () => {
const resp = await handler(
new Request(
"https://fresh.deno.dev/layeredMdw/layer2-with-params/tenant1/resource1",
),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const _body = await resp.text();
// assert that outer has access to all params
assertEquals(
resp.headers.get("middlewareParams_outer"),
JSON.stringify({ tenantId: "tenant1", id: "resource1" }),
);
// assert that inner also has access to all params
assertEquals(
resp.headers.get("middlewareParams_inner"),
JSON.stringify({ tenantId: "tenant1", id: "resource1" }),
);
assertEquals(resp.headers.get("server"), "fresh test server");
},
});
Deno.test({
name: "middleware nesting order",
fn: async () => {
const resp = await handler(
new Request(
"https://fresh.deno.dev/layeredMdw/nesting/acme/production/abc",
),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
const body = await resp.text();
assertStringIncludes(body, "<div>1234</div>");
},
});
Deno.test("/not_found", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/not_found"));
assert(resp);
assertEquals(resp.status, 404);
const body = await resp.text();
assertStringIncludes(body, "404 not found: /not_found");
assertStringIncludes(body, "Hello Dino");
assertStringIncludes(body, "State root: root_mw");
});
Deno.test("middleware destination", async (t) => {
await t.step("static", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/foo.txt"));
assert(resp);
assertEquals(resp.headers.get("destination"), "static");
await resp.body?.cancel();
});
await t.step("route", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/"));
assert(resp);
assertEquals(resp.headers.get("destination"), "route");
await resp.body?.cancel();
});
await t.step("notFound", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/bar/bar"));
assert(resp);
assertEquals(resp.headers.get("destination"), "notFound");
await resp.body?.cancel();
});
});
Deno.test({
name: "middleware catch error",
fn: async () => {
const resp = await handler(
new Request(
"https://fresh.deno.dev/middleware-error-handler",
),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.InternalServerError);
const body = await resp.text();
assertStringIncludes(
body,
"500 internal error: don't show the full error for security purposes",
);
},
});
Deno.test({
name: "404 from middleware",
fn: async () => {
const resp = await handler(
new Request(
"https://fresh.deno.dev/404-from-middleware",
),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.NotFound);
const body = await resp.text();
assertStringIncludes(
body,
"404 not found: /404-from-middleware",
);
},
});
Deno.test({
name: "404 from throw",
fn: async () => {
const resp = await handler(
new Request(
"https://fresh.deno.dev/404_from_throw",
),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.NotFound);
const body = await resp.text();
assertStringIncludes(
body,
"404 not found: /404_from_throw",
);
},
});
Deno.test({
name: "404 from middleware throw",
fn: async () => {
const resp = await handler(
new Request(
"https://fresh.deno.dev/404-from-middleware-throw",
),
);
assert(resp);
assertEquals(resp.status, STATUS_CODE.NotFound);
const body = await resp.text();
assertStringIncludes(
body,
"404 not found: /404-from-middleware-throw",
);
},
});
Deno.test("jsx pragma works", async (t) => {
// Preparation
const { serverProcess, lines, address } = await startFreshServer({
args: ["run", "-A", "./tests/fixture_jsx_pragma/main.ts"],
});
await delay(100);
await t.step("ssr", async () => {
const resp = await fetch(address);
assertEquals(resp.status, STATUS_CODE.OK);
const text = await resp.text();
assertStringIncludes(text, "Hello World");
assertStringIncludes(text, "ssr");
});
const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
const page = await browser.newPage();
await page.goto(address, {
waitUntil: "networkidle2",
});
await t.step("island is revived", async () => {
await page.waitForSelector("#csr");
});
await browser.close();
serverProcess.kill("SIGTERM");
await serverProcess.status;
// Drain the lines stream
for await (const _ of lines) { /* noop */ }
});
Deno.test("preloading javascript files", async () => {
// Preparation
const { serverProcess, lines, address } = await startFreshServer({
args: ["run", "-A", "./tests/fixture/main.ts"],
});
const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
const page = await browser.newPage();
try {
// request js file to start esbuild execution
await page.goto(address, {
waitUntil: "networkidle2",
});
await delay(5000); // wait running esbuild
await page.goto(address, {
waitUntil: "networkidle2",
});
const preloads: string[] = await page.$$eval(
'link[rel="modulepreload"]',
(elements) => elements.map((element) => element.getAttribute("href")),
);
assert(
preloads.some((url) => url.match(/\/_frsh\/js\/.*\/main\.js/)),
"preloads does not include main.js",
);
assert(
preloads.some((url) => url.match(/\/_frsh\/js\/.*\/island-.*\.js/)),
"preloads does not include island-*.js",
);
assert(
preloads.some((url) => url.match(/\/_frsh\/js\/.*\/chunk-.*\.js/)),
"preloads does not include chunk-*.js",
);
} finally {
await browser.close();
serverProcess.kill("SIGTERM");
await serverProcess.status;
// Drain the lines stream
for await (const _ of lines) { /* noop */ }
}
});
Deno.test("PORT environment variable", async () => {
const PORT = "8765";
// Preparation
const { serverProcess, lines } = await startFreshServer({
args: ["run", "-A", "./tests/fixture/main.ts"],
env: { PORT },
});
await delay(100);
const resp = await fetch("http://localhost:" + PORT);
await resp.body?.cancel();
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
await resp.body!.cancel();
serverProcess.kill("SIGTERM");
await serverProcess.status;
// Drain the lines stream
for await (const _ of lines) { /* noop */ }
});
Deno.test(
"throw on route export 'handlers' instead of 'handler'",
async () => {
const result = await new Deno.Command(Deno.execPath(), {
args: ["run", "-A", "./tests/fixture_invalid_handlers/main.ts"],
stderr: "piped",
stdout: "piped",
}).output();
assertEquals(result.code, 1);
const text = new TextDecoder().decode(result.stderr);
assertMatch(text, /Did you mean "handler"\?/);
},
);
Deno.test("rendering custom _500.tsx page for default handlers", async (t) => {
await withFakeServe("./tests/fixture_custom_500/main.ts", async (server) => {
await t.step("SSR error is shown", async () => {
const resp = await server.get("/");
assertEquals(resp.status, STATUS_CODE.InternalServerError);
const text = await resp.text();
assertStringIncludes(text, "Custom 500: Pickle Rick!");
});
await t.step("error page is shown with error message", async () => {
const doc = await server.getHtml("/");
const text = doc.querySelector(".custom-500")?.textContent!;
assertStringIncludes(text, "Custom 500: Pickle Rick!");
});
});
});
Deno.test("renders error boundary", async () => {
await withPageName("./tests/fixture/main.ts", async (page, address) => {
await page.goto(`${address}/error_boundary`);
const text = await page.$eval("p", (el) => el.textContent);
assertEquals(text, "it works");
});
});
Deno.test("Resolves routes with non-latin characters", async () => {
await withFakeServe("./tests/fixture/main.ts", async (server) => {
// Check that we can navigate to the page
const doc = await server.getHtml(`/umlaut-äöüß`);
assertSelector(doc, "h1");
assertTextMany(doc, "h1", ["it works"]);
// Check the manifest
const mod = (await import("./fixture/fresh.gen.ts")).default;
assert(
"./routes/umlaut-äöüß.tsx" in mod.routes,
"Umlaut route not found",
);
});
});
Deno.test("Generate a single nonce value per page", async () => {
await withFakeServe("./tests/fixture/main.ts", async (server) => {
const doc = await server.getHtml("/");
const nonceValues = Array.from(
new Set(
Array.from(doc.querySelectorAll("[nonce]")).map((el) =>
el.getAttribute("nonce")
),
),
);
assertEquals(
nonceValues.length,
1,
`Found more than 1 nonce value per render`,
);
});
});
Deno.test("Adds nonce to inline scripts", async () => {
await withFakeServe("./tests/fixture/main.ts", async (server) => {
const doc = await server.getHtml(`/nonce_inline`);
const stateScript = doc.querySelector("[id^=__FRSH_STATE]")!;
const nonce = stateScript.getAttribute("nonce")!;
const el = doc.querySelector("#inline-script")!;
const inlineNonce = el.getAttribute("nonce")!;
assertEquals(inlineNonce, nonce);
});
});
Deno.test({
name: "support string based event handlers during SSR",
async fn() {
await withPageName("./tests/fixture/main.ts", async (page, address) => {
await page.goto(`${address}/event_handler_string`);
await page.waitForSelector("p");
await page.click("button");
await waitForText(page, "p", "it works");
});
},
});
Deno.test({
name: "Log error in browser console on string event handlers",
async fn() {
await withPageName("./tests/fixture/main.ts", async (page, address) => {
const logs: { type: string; message: string }[] = [];
page.on("console", (ev) => {
logs.push({ type: ev.type(), message: ev.text() });
});
page.on("pageerror", (ev) => {
logs.push({ type: "error", message: ev.toString() });
});
await page.goto(`${address}/event_handler_string_island`);
await page.waitForSelector("p");
await page.click("button");
await waitForText(page, "p", "it works");