-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathexpress.test.js
More file actions
1419 lines (1236 loc) · 47.8 KB
/
express.test.js
File metadata and controls
1419 lines (1236 loc) · 47.8 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
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
/*
* Copyright (c) 2022, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import fse from 'fs-extra'
import https from 'https'
import nock from 'nock'
import os from 'os'
import path from 'path'
import sinon from 'sinon'
import superagent from 'superagent'
import request from 'supertest'
import express from 'express'
import {PersistentCache} from '../../utils/ssr-cache'
import {CachedResponse} from '../../utils/ssr-server'
// We need to mock isRemote in some tests, so we need to import it directly from
// the file it was defined in, because of the way jest works.
import * as ssrServerUtils from '../../utils/ssr-server/utils'
import * as ssrConfig from '../../utils/ssr-config'
import * as ssrNamespacePaths from '../../utils/ssr-namespace-paths'
import {RemoteServerFactory, REMOTE_REQUIRED_ENV_VARS} from './build-remote-server'
import {X_MOBIFY_QUERYSTRING} from './constants'
import {
RESOLVED_PROMISE,
generateCacheKey,
getResponseFromCache,
sendCachedResponse,
cacheResponseWhenDone,
respondFromBundle,
getRuntime
} from './express'
import {randomUUID} from 'crypto'
// Mock static assets (require path is relative to the 'ssr' directory)
const mockStaticAssets = {}
jest.mock('../static/assets.json', () => mockStaticAssets, {virtual: true})
const TEST_PORT = 3444
const testFixtures = path.resolve(process.cwd(), 'src/ssr/server/test_fixtures')
/**
* An HTTPS.Agent that allows self-signed certificates
* @type {module:https.Agent}
*/
const httpsAgent = new https.Agent({
rejectUnauthorized: false
})
const opts = (overrides = {}) => {
const defaults = {
buildDir: './src/ssr/server/test_fixtures',
mobify: {
ssrEnabled: true,
ssrOnly: ['main.js.map', 'ssr.js', 'ssr.js.map'],
ssrShared: ['main.js', 'ssr-loader.js', 'worker.js'],
ssrParameters: {
proxyConfigs: [
{
protocol: 'https',
host: 'test.proxy.com',
path: 'base'
},
{
protocol: 'https',
// This is intentionally an unreachable host
host: '0.0.0.0',
path: 'base2'
},
{
protocol: 'https',
host: 'test.proxy.com',
path: 'base3',
caching: true
}
]
}
},
sslFilePath: './src/ssr/server/test_fixtures/localhost.pem',
quiet: true,
port: TEST_PORT,
protocol: 'https',
fetchAgents: {
https: httpsAgent
},
defaultCacheTimeSeconds: 123,
enableLegacyRemoteProxying: false,
useSLASPrivateClient: false
}
return {
...defaults,
...overrides
}
}
const mkdtempSync = () => fse.mkdtempSync(path.resolve(os.tmpdir(), 'ssr-server-tests-'))
beforeAll(() => {
jest.spyOn(ssrConfig, 'getConfig').mockReturnValue({})
// The SSR app applies patches on creation. Those patches are specific to an
// environment (Lambda or not) and we need to ensure that the non-lambda patches
// are applied for testing. Creating and immediately discarding an app in
// local mode here applies the correct patches for all tests.
RemoteServerFactory._createApp(opts())
})
describe('_createApp validates the options object', () => {
let savedEnvironment
beforeEach(() => {
savedEnvironment = Object.assign({}, process.env)
process.env = {
LISTEN_ADDRESS: '',
EXTERNAL_DOMAIN_NAME: ''
}
})
afterEach(() => {
process.env = savedEnvironment
})
const invalidOptions = [
{
name: 'mobify',
options: opts({mobify: undefined})
},
{
name: 'mobify',
options: opts({mobify: 'a string'})
},
{
name: 'buildDir empty',
options: opts({buildDir: ''})
}
]
invalidOptions.forEach(({name, options}) => {
test(`_createApp validates missing or invalid field "${name}"`, () => {
expect(() => RemoteServerFactory._createApp(options)).toThrow()
})
})
})
describe('_createApp validates environment variables', () => {
let savedEnvironment
beforeEach(() => {
savedEnvironment = Object.assign({}, process.env)
})
afterEach(() => {
process.env = savedEnvironment
})
REMOTE_REQUIRED_ENV_VARS.forEach((envVar) => {
test(`SSR Server verifies environment variable "${envVar}"`, () => {
// Set truthy values for all the env vars except the one we're testing.
const vars = REMOTE_REQUIRED_ENV_VARS.filter((name) => name !== envVar).map((name) => ({
[name]: 'value'
}))
// AWS_LAMBDA_FUNCTION_NAME indicates the server is running remotely on Lambda
vars.push({AWS_LAMBDA_FUNCTION_NAME: 'pretend-to-be-remote'})
process.env = Object.assign({}, savedEnvironment, ...vars)
expect(() => RemoteServerFactory._createApp(opts())).toThrow(envVar)
})
})
})
describe('SSRServer operation', () => {
const savedEnvironment = Object.assign({}, process.env)
const sandbox = sinon.createSandbox()
afterEach(() => {
sandbox.restore()
jest.resetModules()
nock.cleanAll()
})
afterAll(() => {
process.env = savedEnvironment
})
beforeEach(() => {
RemoteServerFactory._setRequestId = jest.fn().mockImplementation((_app) => {
_app.use((req, res, next) => {
res.locals.requestId = randomUUID()
next()
})
})
// Ensure the environment is clean
process.env = {
LISTEN_ADDRESS: '',
EXTERNAL_DOMAIN_NAME: ''
}
})
test('_createApp creates an express app', () => {
const options = opts()
const app = RemoteServerFactory._createApp(options)
const expected = `max-age=${options.defaultCacheTimeSeconds}, s-maxage=${options.defaultCacheTimeSeconds}`
expect(app.options.defaultCacheControl).toEqual(expected)
})
test('SSRServer tracks responses', () => {
const route = jest.fn().mockImplementation((req, res) => {
res.send('<div>hello world</div>')
return Promise.resolve()
})
const app = RemoteServerFactory._createApp(opts())
app.get('/*', route)
const response1 = {
locals: {
requestId: 1
},
once: () => null
}
const response2 = {
locals: {
requestId: 2
},
once: () => null
}
expect(app._requestMonitor._pendingResponses.ids).toEqual([])
app._requestMonitor._responseFinished(response1)
expect(app._requestMonitor._pendingResponses.ids).toEqual([])
const promise1 = app._requestMonitor._waitForResponses()
expect(promise1).toBe(RESOLVED_PROMISE)
app._requestMonitor._responseStarted(response1)
expect(app._requestMonitor._pendingResponses.ids).toEqual([1])
const promise2 = app._requestMonitor._waitForResponses()
expect(promise2).not.toBe(RESOLVED_PROMISE)
app._requestMonitor._responseStarted(response2)
expect(app._requestMonitor._pendingResponses.ids).toEqual([1, 2])
const promise3 = app._requestMonitor._waitForResponses()
expect(promise3).toBe(promise2)
app._requestMonitor._responseFinished(response1)
expect(app._requestMonitor._pendingResponses.ids).toEqual([2])
app._requestMonitor._responseFinished(response1)
expect(app._requestMonitor._pendingResponses.ids).toEqual([2])
app._requestMonitor._responseFinished(response2)
expect(app._requestMonitor._pendingResponses.ids).toEqual([])
// If the promise doesn't resolve, this test will timeout
return promise2
})
test(`The Remote SSRServer always uses https`, () => {
REMOTE_REQUIRED_ENV_VARS.forEach((envVar) => {
process.env[envVar] = 'value'
})
const app = RemoteServerFactory._createApp(opts({protocol: 'http'}))
expect(app.options.protocol).toBe('https')
process.env = savedEnvironment
})
test('SSRServer renders correctly', () => {
const body = '<div>hello world</div>'
const route = jest.fn().mockImplementation((req, res) => {
res.send(body)
})
const app = RemoteServerFactory._createApp(opts())
app.get('/*', route)
return request(app)
.get('/')
.expect(200)
.then((res) => {
expect(res.headers['x-powered-by']).toBeUndefined()
expect(res.text).toBe(body)
expect(route).toHaveBeenCalled()
})
})
test('SSRServer renders with the react rendering', () => {
const app = RemoteServerFactory._createApp(opts())
app.get('/*', RemoteServerFactory.render)
expect(app.__renderer).toBeUndefined()
return request(app)
.get('/')
.expect(200)
.then((res) => {
expect(res.text).toBe('OK')
expect(app.__renderer).toBeDefined()
})
})
test('SSRServer rendering blocks cookie setting by default', () => {
const route = (req, res) => {
res.setHeader('set-cookie', 'blah123')
res.sendStatus(200)
}
const app = RemoteServerFactory._createApp(opts())
app.get('/*', route)
jest.spyOn(console, 'warn')
return request(app)
.get('/')
.expect(200)
.then((res) => {
expect(console.warn.mock.calls[0][0]).toContain(`Discarding "Set-Cookie: blah123"`)
expect(res.headers['Set-Cookie']).toBeUndefined()
expect(res.headers['set-cookie']).toBeUndefined()
})
})
test('SSRServer rendering allows setting cookies with MRT_ALLOW_COOKIES env', () => {
process.env = {
MRT_ALLOW_COOKIES: 'true'
}
const route = (req, res) => {
res.setHeader('set-cookie', 'blah123')
res.sendStatus(200)
}
const app = RemoteServerFactory._createApp(opts())
app.get('/*', route)
return request(app)
.get('/')
.expect(200)
.then((res) => {
expect(res.headers['set-cookie']).toEqual(['blah123'])
})
})
test('SSRServer does not allow multi-value headers', () => {
const route = (req, res) => {
res.set('content-type', 'application/octet-stream')
res.set('content-type', 'text/plain')
res.send('<div>hello world</div>')
}
const app = RemoteServerFactory._createApp(opts())
app.get('*', route)
return request(app)
.get('/')
.expect(200)
.then((res) => {
expect(res.headers['content-type']).toBe('text/plain; charset=utf-8')
})
})
test('SSRServer honours any x-mobify-querystring header', () => {
const route = jest.fn().mockImplementation((req, res) => {
res.send('<div> Hello world </div>')
})
const app = RemoteServerFactory._createApp(opts())
app.get('/*', route)
return request(app)
.get('/')
.set(X_MOBIFY_QUERYSTRING, 'z=1&y=2&x=3')
.expect(200)
.then(() => {
expect(route.mock.calls[0][0].query).toEqual({z: '1', y: '2', x: '3'})
})
})
describe('Running remotely', () => {
let isRemoteMock
let savedEnvironment
beforeEach(() => {
isRemoteMock = jest.spyOn(ssrServerUtils, 'isRemote').mockImplementation(() => true)
savedEnvironment = Object.assign({}, process.env)
Object.assign(process.env, {
BUNDLE_ID: 1,
DEPLOY_TARGET: 1,
EXTERNAL_DOMAIN_NAME: 'http://www.example.com',
MOBIFY_PROPERTY_ID: 'example'
})
})
afterEach(() => {
isRemoteMock.mockRestore()
process.env = savedEnvironment
})
test('should not proxy', () => {
const app = RemoteServerFactory._createApp(opts())
return request(app).get('/mobify/proxy/base/test/path').expect(501)
})
})
test('SSRServer handles /mobify/ping', () => {
const app = RemoteServerFactory._createApp(opts())
return request(app).get('/mobify/ping').expect(200)
})
describe('SSRServer worker.js handling', () => {
let tmpDir
beforeEach(() => {
tmpDir = mkdtempSync()
})
afterEach(() => {
fse.removeSync(tmpDir)
})
const cases = [
{
file: 'worker.js',
content: '// a service worker',
name: 'Should serve the service worker',
requestPath: '/worker.js'
},
{
file: 'worker.js.map',
content: '// a service worker source map',
name: 'Should serve the service worker source map',
requestPath: '/worker.js.map'
}
]
cases.forEach(({file, content, name, requestPath}) => {
test(`${name}`, () => {
const fixture = path.join(__dirname, 'test_fixtures')
const buildDir = path.join(tmpDir, 'build')
fse.copySync(fixture, buildDir)
const updatedFile = path.resolve(buildDir, file)
fse.writeFileSync(updatedFile, content)
const app = RemoteServerFactory._createApp(opts({buildDir}))
app.get('/worker.js(.map)?', RemoteServerFactory.serveServiceWorker)
return request(app)
.get(requestPath)
.expect(200)
.then((res) => expect(res.text).toEqual(content))
})
test(`${name} (and handle 404s correctly)`, () => {
const app = RemoteServerFactory._createApp(opts({buildDir: tmpDir}))
app.get('/worker.js(.map)?', RemoteServerFactory.serveServiceWorker)
return request(app).get(requestPath).expect(404)
})
})
})
test('SSRServer creates cache on demand', () => {
const app = RemoteServerFactory._createApp(opts())
expect(app._applicationCache).toBeUndefined()
expect(app.applicationCache).toBeInstanceOf(PersistentCache)
expect(app._applicationCache).toBe(app.applicationCache)
})
test('should support redirects to bundle assets', () => {
const app = RemoteServerFactory._createApp(opts())
const route = (req, res) => {
respondFromBundle({req, res})
}
app.get('/*', route)
return request(app)
.get('/some-bundle-path.jpg')
.then((response) => {
expect(response.status).toBe(301)
expect(
response.headers['location'].endsWith(
'/mobify/bundle/development/some-bundle-path.jpg'
)
).toBe(true)
})
})
test('should support other redirects', () => {
const app = RemoteServerFactory._createApp(opts())
const route = (req, res) => {
res.redirect(302, '/elsewhere')
}
app.get('/*', route)
return request(app)
.get('/some-bundle-path.jpg')
.then((response) => {
expect(response.status).toBe(302)
expect(response.headers['location'].endsWith('/elsewhere')).toBe(true)
})
})
test('should warn about non-strict SSL', () => {
const app = RemoteServerFactory._createApp(opts())
const route = (req, res) => {
res.redirect(302, '/elsewhere')
}
app.get('/*', route)
return request(app)
.get('/some-bundle-path.jpg')
.then((response) => {
expect(response.status).toBe(302)
expect(response.headers['location'].endsWith('/elsewhere')).toBe(true)
})
})
test('should support error codes', () => {
const app = RemoteServerFactory._createApp(opts())
const route = (request, response) => {
response.sendStatus(500)
}
app.get('/*', route)
return request(app)
.get('/')
.then((response) => {
expect(response.status).toBe(500)
})
})
test('should strip cookies before passing the request to the handler by default', () => {
const app = RemoteServerFactory._createApp(opts())
const route = (req, res) => {
expect(req.headers.cookie).toBeUndefined()
res.sendStatus(200)
}
app.get('/*', route)
return request(app)
.get('/')
.set('cookie', 'xyz=456')
.then((response) => {
expect(response.status).toBe(200)
expect(response.headers['set-cookie']).toBeUndefined()
})
})
test('should allow cookies in the request with MRT_ALLOW_COOKIES env', () => {
process.env = {MRT_ALLOW_COOKIES: 'true'}
const app = RemoteServerFactory._createApp(opts())
const route = (req, res) => {
expect(req.headers.cookie).toBe('xyz=456')
res.sendStatus(200)
}
app.get('/*', route)
return request(app)
.get('/')
.set('cookie', 'xyz=456')
.then((response) => {
expect(response.status).toBe(200)
expect(response.headers['set-cookie']).toBeUndefined()
})
})
test('should fix host and origin headers before passing the request to the handler', () => {
const app = RemoteServerFactory._createApp(opts())
const route = (req, res) => {
expect(req.headers.host).toEqual(app.options.appHostname)
expect(req.headers.origin).toEqual(app.options.appOrigin)
res.sendStatus(200)
}
app.get('/*', route)
return request(app)
.get('/')
.set({
host: 'somewhere.over.the.rainbow',
origin: 'https://somewhere.over.the.rainbow'
})
.then((response) => {
expect(response.status).toBe(200)
expect(response.headers['set-cookie']).toBeUndefined()
})
})
test('should set xForwardedOrigin based on defined x-forwarded-host and x-forwarded-proto headers', () => {
process.env = {
MRT_ALLOW_COOKIES: 'true'
}
const forwardedHost = 'www.example.com'
const forwardedProto = 'https'
const app = RemoteServerFactory._createApp(opts())
const route = (req, res) => {
expect(req.headers['x-forwarded-host']).toBe(forwardedHost)
expect(res.locals.xForwardedOrigin).toBe(`${forwardedProto}://${forwardedHost}`)
res.sendStatus(200)
}
app.get('/*', route)
return request(app)
.get('/')
.set('x-forwarded-host', forwardedHost)
.set('x-forwarded-proto', 'https')
.then((response) => {
expect(response.status).toBe(200)
})
})
test('should set xForwardedOrigin based on defined x-forwarded-host and undefined x-forwarded-proto headers', () => {
process.env = {
MRT_ALLOW_COOKIES: 'true'
}
const options = opts()
const forwardedHost = 'www.example.com'
const app = RemoteServerFactory._createApp(options)
const route = (req, res) => {
expect(req.headers['x-forwarded-host']).toBe(forwardedHost)
expect(res.locals.xForwardedOrigin).toBe(`${options.protocol}://${forwardedHost}`)
res.sendStatus(200)
}
app.get('/*', route)
return request(app)
.get('/')
.set('x-forwarded-host', forwardedHost)
.then((response) => {
expect(response.status).toBe(200)
})
})
test(`should reject POST requests to /`, () => {
const app = RemoteServerFactory._createApp(opts())
const route = (req, res) => {
res.status(200).end()
}
app.get('/*', route)
return request(app)
.post('/')
.then((response) => {
expect(response.status).toBe(405)
})
})
test('serveStaticFile serves static files from the build directory', () => {
const app = RemoteServerFactory._createApp(opts())
const faviconPath = path.resolve(testFixtures, 'favicon.ico')
app.get('/thing', RemoteServerFactory.serveStaticFile('favicon.ico'))
return request(app)
.get('/thing')
.buffer(true)
.parse(superagent.parse.image)
.expect(200)
.then((res) => {
const iconData = fse.readFileSync(faviconPath)
expect(res.body).toEqual(iconData)
})
})
test('serveStaticFile returns 404 if the file does not exist', () => {
const app = RemoteServerFactory._createApp(opts())
app.get('/thing', RemoteServerFactory.serveStaticFile('this-does-not-exist.ico'))
return request(app).get('/thing').expect(404)
})
})
describe('SSRServer persistent caching', () => {
const namespace = 'test'
const keyFromURL = (url) => encodeURIComponent(url)
/**
* A cache decorator for a route function that uses the percent-encoded req.url
* as keys for all cache entries (this makes testing easier).
*/
const cachedRoute = (route) => (req, res) => {
const shouldCache = !req.query.noCache
const cacheArgs = {
req,
res,
namespace,
key: keyFromURL(req.url)
}
const shouldCacheResponse = (req, res) => res.statusCode >= 200 && res.statusCode < 300
return Promise.resolve()
.then(() => getResponseFromCache(cacheArgs))
.then((entry) => {
if (entry.found) {
sendCachedResponse(entry)
} else {
if (shouldCache) {
cacheResponseWhenDone({
shouldCacheResponse,
...cacheArgs
})
}
return route(req, res)
}
})
}
/**
* A test route that returns different content types based on query params.
*/
const routeImplementation = (req, res) => {
const status = parseInt(req.query.status || 200)
switch (req.query.type) {
case 'image':
res.status(status)
res.setHeader('content-type', 'image/png')
res.send(fse.readFileSync(path.join(testFixtures, 'mobify.png')))
break
case 'html':
res.status(status)
res.setHeader('x-rendered', 'true')
res.setHeader('cache-control', 's-maxage=60')
res.send('<div> Hello world </div>')
break
case '500':
res.sendStatus(500)
break
case '400':
res.sendStatus(400)
break
default:
res.sendStatus(status)
break
}
}
const sandbox = sinon.createSandbox()
let app, route
beforeEach(() => {
route = jest.fn().mockImplementation(routeImplementation)
const withCaching = cachedRoute(route)
app = RemoteServerFactory._createApp(opts())
app.get('/*', withCaching)
})
afterEach(() => {
sandbox.restore()
app.applicationCache.close()
app = null
route = null
})
const testCases = [
{
name: 'Should put HTML responses into the cache after rendering',
url: '/cacheme/?type=html',
expectOk: true,
expectHeaders: {
'x-mobify-from-cache': 'false',
'x-rendered': 'true',
'content-type': 'text/html; charset=utf-8'
},
expectToBeCached: false,
expectRenderCallCount: 1
},
{
name: 'Should put binary responses into the cache after rendering',
url: '/cacheme/?type=image',
expectOk: true,
expectHeaders: {
'x-mobify-from-cache': 'false',
'content-type': 'image/png'
},
expectToBeCached: false,
expectRenderCallCount: 1
},
{
name: 'Should skip putting responses into the cache when noCache is set',
url: '/cacheme/?type=image&noCache=1',
expectOk: true,
expectHeaders: {
'x-mobify-from-cache': 'false',
'content-type': 'image/png'
},
expectToBeCached: false,
expectRenderCallCount: 1
},
{
name: 'Should return a response even when the cache put fails',
url: '/cacheme/?type=image&a=1',
expectOk: true,
expectHeaders: {
'x-mobify-from-cache': 'false',
'content-type': 'image/png'
},
expectToBeCached: false,
expectRenderCallCount: 1,
forcePutFailure: true
},
{
name: 'Should serve responses from the cache, including HTTP headers',
url: '/cacheme/?type=html',
expectOk: true,
expectHeaders: {
'x-mobify-from-cache': 'false',
'content-type': 'text/html; charset=utf-8'
},
expectToBeCached: false,
expectRenderCallCount: 1,
preCache: {
data: Buffer.from('<html>456</html>'),
metadata: {
status: 200,
headers: {
'x-precached': 'false',
'content-type': 'text/html; charset=utf-8'
}
}
}
},
{
name: 'Should serve responses from the cache without cached HTTP headers',
url: '/cacheme/?type=html',
expectOk: true,
expectHeaders: {
'x-mobify-from-cache': 'false'
},
expectToBeCached: false,
expectRenderCallCount: 1,
preCache: {
data: Buffer.from('<html>123</html>')
}
},
{
name: 'Should serve empty responses from the cache without errors',
url: '/cacheme/?type=none',
expectOk: true,
expectHeaders: {
'x-mobify-from-cache': 'false'
},
expectToBeCached: false,
expectRenderCallCount: 1,
preCache: {
data: undefined,
metadata: {
status: 200,
headers: {
'x-precached': 'true'
}
}
}
}
]
testCases.forEach((testCase) =>
test(`${testCase.name}`, () => {
let url = testCase.url
return (
Promise.resolve()
.then(() => {
const preCache = testCase.preCache
if (preCache) {
return app.applicationCache.put({
namespace,
key: keyFromURL(url),
metadata: preCache.metadata,
data: preCache.data
})
}
})
.then(() => {
sandbox.stub(app.applicationCache, 'put')
if (testCase.forcePutFailure) {
app.applicationCache.put
.onFirstCall()
.callsFake(() => Promise.reject('Fake put error'))
}
app.applicationCache.put.callThrough()
})
.then(() => {
// Buffer and parse everything as binary for easy comparison
// across content types.
return request(app)
.get(url)
.buffer(true)
.parse(superagent.parse['application/octet-stream'])
})
// Wait for any caching to complete
.then((response) =>
app._requestMonitor._waitForResponses().then(() => response)
)
// Handle and verify the response
.then((response) => {
expect(response.ok).toEqual(testCase.expectOk)
expect(route.mock.calls).toHaveLength(testCase.expectRenderCallCount)
expect(response.headers).toMatchObject(testCase.expectHeaders)
return Promise.all([
response,
app.applicationCache.get({
key: keyFromURL(url),
namespace
})
])
})
.then(([, entry]) => {
// Verify the response data against the cache
expect(entry.found).toBe(false)
})
)
})
)
const errorCases = [
{url: '/?type=500', status: 500},
{url: '/?type=400', status: 400}
]
errorCases.forEach(({url, status}) => {
test(`should not cache responses with ${status} status codes`, () => {
return request(app)
.get(url)
.then((res) => app._requestMonitor._waitForResponses().then(() => res))
.then((res) => {
expect(res.status).toBe(status)
expect(res.headers['x-mobify-from-cache']).toBe('false')
})
.then(() =>
app.applicationCache.get({
key: keyFromURL(url),
namespace
})
)
.then((entry) => expect(entry.found).toBe(false))
})
})
test('Try to send non-cached response', () => {
expect(() => sendCachedResponse(new CachedResponse({}))).toThrow('non-cached')
})
})
describe('generateCacheKey', () => {
const mockRequest = (overrides) => {
return {
url: '/test?a=1',
query: {},
headers: {},
get: function (key) {
return this.headers[key]
},
...overrides
}
}
test('returns expected results', () => {
expect(generateCacheKey(mockRequest({url: '/test/1?id=abc'})).indexOf('/test/1')).toBe(0)
})
test('path affects key', () => {
const result1 = generateCacheKey(mockRequest({url: '/test2a/'}))
expect(generateCacheKey(mockRequest({url: '/testab/'}))).not.toEqual(result1)
})
test('query affects key', () => {
const result1 = generateCacheKey(mockRequest({url: '/test3?a=1'}))
expect(generateCacheKey(mockRequest({url: '/test3?a=2'}))).not.toEqual(result1)
})
test('request class affects key', () => {
const result1 = generateCacheKey(mockRequest())
const request2 = mockRequest({
headers: {
'x-mobify-request-class': 'bot'
}
})
expect(generateCacheKey(request2)).not.toEqual(result1)
expect(generateCacheKey(request2, {ignoreRequestClass: true})).toEqual(result1)
})
test('extras affect key', () => {
const result1 = generateCacheKey(mockRequest())
expect(generateCacheKey(mockRequest(), {extras: ['123']})).not.toEqual(result1)
})
})
describe('getRuntime', () => {
let originalEnv
let originalEval = global.eval
// Mock the DevSeverFactory via `eval` so we don't have to include it as a dev
// dependency which will cause circular dependency warnings.
const MockDevServerFactory = {
name: 'MockDevServerFactory',
returnMyName() {
return this.name
}
}
const mockEval = () => ({
main: {
require: () => ({DevServerFactory: MockDevServerFactory})
}