-
-
Notifications
You must be signed in to change notification settings - Fork 473
/
jest.setup.ts
107 lines (95 loc) · 2.76 KB
/
jest.setup.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
import * as fs from 'fs'
import * as path from 'path'
import { invariant } from 'outvariant'
import { CreateBrowserApi, createBrowser } from 'page-with'
import { ServerApi } from '@open-draft/test-server'
import { SERVICE_WORKER_BUILD_PATH } from '../config/constants'
import {
createWorkerConsoleServer,
workerConsoleSpy,
} from './support/workerConsole'
let browser: CreateBrowserApi
let workerConsoleServer: ServerApi
beforeAll(async () => {
workerConsoleServer = await createWorkerConsoleServer()
const browserInstance = await createBrowser({
serverOptions: {
router(app) {
// Prevent Express from responding with cached 304 responses.
app.set('etag', false)
app.get('/mockServiceWorker.js', (req, res) => {
const workerScript = fs.readFileSync(
SERVICE_WORKER_BUILD_PATH,
'utf8',
)
// Edit the worker script to signal any console messages
// to the standalone server. This way tests can spy on the
// console messages from the worker.
res.set('Content-Type', 'application/javascript').send(`
${workerScript}
// EVERYTHING BELOW THIS LINE IS APPENDED TO THE WORKER SCRIPT
// ONLY DURING THE TEST RUN.
const originals = {}
Object.keys(console).forEach((methodName) => {
originals[methodName] = console[methodName]
console[methodName] = (...args) => {
fetch('${workerConsoleServer.http.makeUrl('/console/')}' + methodName, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(args)
})
originals[methodName](...args)
}
})
`)
})
},
webpackConfig: {
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader',
options: {
configFile: path.resolve(__dirname, '../tsconfig.json'),
transpileOnly: true,
},
},
],
},
],
},
resolve: {
alias: {
msw: path.resolve(__dirname, '..'),
},
extensions: ['.ts', '.js'],
},
},
},
}).catch((error) => {
console.error('Failed to create browser:', error)
})
invariant(
browserInstance,
'Failed to run the "beforeAll" hook: the browser instance is missing or malformed.',
browserInstance,
)
browser = browserInstance
})
afterEach(() => {
workerConsoleSpy.clear()
})
afterAll(async () => {
invariant(
browser,
'Failed to run the "afterAll" hook: the browser instance does not exist.',
browser,
)
await Promise.all([browser.cleanup(), workerConsoleServer.close()])
})