refactor(tests): ⚡️ Add msw and mock authentication
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
NEXT_PUBLIC_AUTH_MOCKING=disabled
|
||||
|
||||
DATABASE_URL=postgresql://postgres:@localhost:5432/typebot
|
||||
|
||||
ENCRYPTION_SECRET=q3t6v9y$B&E)H@McQfTjWnZr4u7x!z%C #256-bits secret (can be generated here: https://www.allkeysgenerator.com/Random/Security-Encryption-Key-Generator.aspx)
|
||||
|
||||
@@ -149,7 +149,7 @@ const IndeterminateCheckbox = React.forwardRef(
|
||||
const resolvedRef: any = ref || defaultRef
|
||||
|
||||
return (
|
||||
<Flex justify="center">
|
||||
<Flex justify="center" data-testid="checkbox">
|
||||
<Checkbox
|
||||
ref={resolvedRef}
|
||||
{...rest}
|
||||
|
||||
30
apps/builder/mocks/index.ts
Normal file
30
apps/builder/mocks/index.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { rest, setupWorker } from 'msw'
|
||||
import { setupServer } from 'msw/node'
|
||||
|
||||
const handlers = () => [
|
||||
rest.get('http://localhost:3000/api/auth/session', (req, res, ctx) => {
|
||||
const authenticatedUser = JSON.parse(
|
||||
typeof localStorage !== 'undefined'
|
||||
? (localStorage.getItem('authenticatedUser') as string)
|
||||
: '{"id":"proUser","name":"John Smith","email":"john@smith.com","emailVerified":null,"image":"https://avatars.githubusercontent.com/u/16015833?v=4","plan":"PRO","stripeId":null}'
|
||||
)
|
||||
return res(
|
||||
ctx.json({
|
||||
user: authenticatedUser,
|
||||
expires: '2022-03-13T17:02:42.317Z',
|
||||
})
|
||||
)
|
||||
}),
|
||||
]
|
||||
|
||||
export const enableMocks = () => {
|
||||
if (typeof window === 'undefined') {
|
||||
const server = setupServer(...handlers())
|
||||
server.listen()
|
||||
} else {
|
||||
const worker = setupWorker(...handlers())
|
||||
worker.start({
|
||||
onUnhandledRequest: 'bypass',
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,9 @@
|
||||
"test": "dotenv -e ./playwright/.env -e .env.local -- yarn playwright test",
|
||||
"test:open": "dotenv -e ./playwright/.env -e .env.local -v PWDEBUG=1 -- yarn playwright test"
|
||||
},
|
||||
"msw": {
|
||||
"workerDirectory": "public"
|
||||
},
|
||||
"dependencies": {
|
||||
"@chakra-ui/css-reset": "^1.1.1",
|
||||
"@chakra-ui/react": "^1.8.1",
|
||||
@@ -50,6 +53,7 @@
|
||||
"micro": "^9.3.4",
|
||||
"micro-cors": "^0.1.1",
|
||||
"models": "*",
|
||||
"msw": "^0.36.8",
|
||||
"next": "^12.0.9",
|
||||
"next-auth": "4.1.2",
|
||||
"nodemailer": "^6.7.2",
|
||||
@@ -69,10 +73,10 @@
|
||||
"styled-components": "^5.3.3",
|
||||
"svg-round-corners": "^0.3.0",
|
||||
"swr": "^1.2.0",
|
||||
"typebot-js": "2.0.21",
|
||||
"use-debounce": "^7.0.1",
|
||||
"use-immer": "^0.6.0",
|
||||
"utils": "*",
|
||||
"typebot-js": "2.0.21"
|
||||
"utils": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.18.1",
|
||||
|
||||
@@ -15,6 +15,9 @@ import { TypebotContext } from 'contexts/TypebotContext'
|
||||
import { useRouter } from 'next/router'
|
||||
import { KBarProvider } from 'kbar'
|
||||
import { actions } from 'libs/kbar'
|
||||
import { enableMocks } from 'mocks'
|
||||
|
||||
if (process.env.NEXT_PUBLIC_AUTH_MOCKING === 'enabled') enableMocks()
|
||||
|
||||
const App = ({ Component, pageProps }: AppProps) => {
|
||||
useRouterProgressBar()
|
||||
|
||||
@@ -9,14 +9,14 @@ const config: PlaywrightTestConfig = {
|
||||
timeout: 5000,
|
||||
},
|
||||
retries: process.env.NO_RETRIES ? 0 : 2,
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
workers: process.env.CI ? 1 : 3,
|
||||
reporter: 'html',
|
||||
maxFailures: process.env.CI ? 10 : undefined,
|
||||
use: {
|
||||
actionTimeout: 0,
|
||||
baseURL: process.env.PLAYWRIGHT_BUILDER_TEST_BASE_URL,
|
||||
trace: 'on-first-retry',
|
||||
storageState: path.join(__dirname, 'playwright/authenticatedState.json'),
|
||||
storageState: path.join(__dirname, 'playwright/proUser.json'),
|
||||
video: 'retain-on-failure',
|
||||
locale: 'en-US',
|
||||
},
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
PLAYWRIGHT_BUILDER_TEST_BASE_URL=http://localhost:3000
|
||||
NEXT_PUBLIC_AUTH_MOCKING=enabled
|
||||
|
||||
# For auth
|
||||
GITHUB_EMAIL=
|
||||
GITHUB_PASSWORD=
|
||||
PLAYWRIGHT_BUILDER_TEST_BASE_URL=http://localhost:3000
|
||||
|
||||
# SMTP Credentials (Generated on https://ethereal.email/)
|
||||
SMTP_HOST=smtp.ethereal.email
|
||||
|
||||
14
apps/builder/playwright/freeUser.json
Normal file
14
apps/builder/playwright/freeUser.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"cookies": [],
|
||||
"origins": [
|
||||
{
|
||||
"origin": "http://localhost:3000",
|
||||
"localStorage": [
|
||||
{
|
||||
"name": "authenticatedUser",
|
||||
"value": "{\"id\":\"freeUser\",\"name\":\"John Smith\",\"email\":\"john@smith.fr\",\"emailVerified\":null,\"image\":\"https://avatars.githubusercontent.com/u/16015833?v=4\",\"plan\":\"FREE\",\"stripeId\":null}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,10 +1,5 @@
|
||||
import { chromium, FullConfig, Page } from '@playwright/test'
|
||||
import { existsSync } from 'fs'
|
||||
import {
|
||||
getSignedInUser,
|
||||
setupDatabase,
|
||||
teardownDatabase,
|
||||
} from './services/database'
|
||||
import { FullConfig } from '@playwright/test'
|
||||
import { setupDatabase, teardownDatabase } from './services/database'
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
require('dotenv').config({ path: '.env' })
|
||||
@@ -12,43 +7,8 @@ require('dotenv').config({ path: '.env' })
|
||||
async function globalSetup(config: FullConfig) {
|
||||
const { baseURL } = config.projects[0].use
|
||||
if (!baseURL) throw new Error('baseURL is missing')
|
||||
if (!process.env.GITHUB_EMAIL || !process.env.GITHUB_PASSWORD)
|
||||
throw new Error(
|
||||
'GITHUB_EMAIL or GITHUB_PASSWORD are missing in the environment. They are required to log in.'
|
||||
)
|
||||
|
||||
await teardownDatabase()
|
||||
|
||||
const signedInUser = await getSignedInUser(process.env.GITHUB_EMAIL as string)
|
||||
if (!signedInUser || !existsSync('./playwright/authenticatedState.json')) {
|
||||
const browser = await chromium.launch()
|
||||
const page = await browser.newPage()
|
||||
await signIn(page)
|
||||
await page.context().storageState({
|
||||
path: './playwright/authenticatedState.json',
|
||||
})
|
||||
}
|
||||
|
||||
await setupDatabase(process.env.GITHUB_EMAIL as string)
|
||||
}
|
||||
|
||||
const signIn = async (page: Page) => {
|
||||
await page.goto(`${process.env.PLAYWRIGHT_BUILDER_TEST_BASE_URL}/signin`)
|
||||
await page.click('text=Continue with GitHub')
|
||||
await page.fill('input[name="login"]', process.env.GITHUB_EMAIL as string)
|
||||
await page.fill(
|
||||
'input[name="password"]',
|
||||
process.env.GITHUB_PASSWORD as string
|
||||
)
|
||||
await page.press('input[name="password"]', 'Enter')
|
||||
try {
|
||||
await page.locator('text=Authorize baptisteArno').click({ timeout: 3000 })
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
await page.waitForNavigation({
|
||||
url: `${process.env.PLAYWRIGHT_BUILDER_TEST_BASE_URL}/typebots`,
|
||||
})
|
||||
await setupDatabase()
|
||||
}
|
||||
|
||||
export default globalSetup
|
||||
|
||||
14
apps/builder/playwright/proUser.json
Normal file
14
apps/builder/playwright/proUser.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"cookies": [],
|
||||
"origins": [
|
||||
{
|
||||
"origin": "http://localhost:3000",
|
||||
"localStorage": [
|
||||
{
|
||||
"name": "authenticatedUser",
|
||||
"value": "{\"id\":\"proUser\",\"name\":\"John Smith\",\"email\":\"john@smith.com\",\"emailVerified\":null,\"image\":\"https://avatars.githubusercontent.com/u/16015833?v=4\",\"plan\":\"PRO\",\"stripeId\":null}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -15,18 +15,25 @@ import { encrypt } from 'utils'
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
export const teardownDatabase = async () => {
|
||||
await prisma.user.deleteMany()
|
||||
await prisma.credentials.deleteMany()
|
||||
await prisma.dashboardFolder.deleteMany()
|
||||
return prisma.typebot.deleteMany()
|
||||
}
|
||||
|
||||
export const setupDatabase = async (userEmail: string) => {
|
||||
const createdUser = await getSignedInUser(userEmail)
|
||||
if (!createdUser) throw new Error("Couldn't find user")
|
||||
process.env.PLAYWRIGHT_USER_ID = createdUser.id
|
||||
export const setupDatabase = async () => {
|
||||
await createUsers()
|
||||
return createCredentials()
|
||||
}
|
||||
|
||||
export const createUsers = () =>
|
||||
prisma.user.createMany({
|
||||
data: [
|
||||
{ id: 'freeUser', email: 'free-user@email.com', name: 'Free user' },
|
||||
{ id: 'proUser', email: 'pro-user@email.com', name: 'Pro user' },
|
||||
],
|
||||
})
|
||||
|
||||
export const getSignedInUser = (email: string) =>
|
||||
prisma.user.findFirst({ where: { email } })
|
||||
|
||||
@@ -44,7 +51,7 @@ export const createTypebots = async (partialTypebots: Partial<Typebot>[]) => {
|
||||
export const createFolders = (partialFolders: Partial<DashboardFolder>[]) =>
|
||||
prisma.dashboardFolder.createMany({
|
||||
data: partialFolders.map((folder) => ({
|
||||
ownerId: process.env.PLAYWRIGHT_USER_ID as string,
|
||||
ownerId: 'proUser',
|
||||
name: 'Folder #1',
|
||||
...folder,
|
||||
})),
|
||||
@@ -63,7 +70,7 @@ const createCredentials = () => {
|
||||
data: [
|
||||
{
|
||||
name: 'test2@gmail.com',
|
||||
ownerId: process.env.PLAYWRIGHT_USER_ID as string,
|
||||
ownerId: 'proUser',
|
||||
type: CredentialsType.GOOGLE_SHEETS,
|
||||
data: encryptedData,
|
||||
iv,
|
||||
@@ -75,10 +82,13 @@ const createCredentials = () => {
|
||||
export const updateUser = (data: Partial<User>) =>
|
||||
prisma.user.update({
|
||||
data,
|
||||
where: { id: process.env.PLAYWRIGHT_USER_ID as string },
|
||||
where: {
|
||||
id: 'proUser',
|
||||
},
|
||||
})
|
||||
|
||||
export const createResults = async ({ typebotId }: { typebotId: string }) => {
|
||||
await prisma.result.deleteMany()
|
||||
await prisma.result.createMany({
|
||||
data: [
|
||||
...Array.from(Array(200)).map((_, idx) => {
|
||||
@@ -137,7 +147,7 @@ const parseTestTypebot = (partialTypebot: Partial<Typebot>): Typebot => ({
|
||||
id: partialTypebot.id ?? 'typebot',
|
||||
folderId: null,
|
||||
name: 'My typebot',
|
||||
ownerId: process.env.PLAYWRIGHT_USER_ID as string,
|
||||
ownerId: 'proUser',
|
||||
theme: defaultTheme,
|
||||
settings: defaultSettings,
|
||||
createdAt: new Date(),
|
||||
@@ -198,7 +208,7 @@ export const importTypebotInDatabase = (
|
||||
const typebot: any = {
|
||||
...JSON.parse(readFileSync(path).toString()),
|
||||
...updates,
|
||||
ownerId: process.env.PLAYWRIGHT_USER_ID,
|
||||
ownerId: 'proUser',
|
||||
}
|
||||
return prisma.typebot.create({
|
||||
data: typebot,
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import test, { expect } from '@playwright/test'
|
||||
import { refreshUser } from '../services/browser'
|
||||
import { Plan } from 'db'
|
||||
import path from 'path'
|
||||
import { updateUser } from '../services/database'
|
||||
|
||||
test.describe('Account page', () => {
|
||||
test('should edit user info properly', async ({ page }) => {
|
||||
await updateUser({
|
||||
name: 'Default Name',
|
||||
image:
|
||||
'https://images.unsplash.com/photo-1521119989659-a83eee488004?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1323&q=80',
|
||||
})
|
||||
await page.goto('/account')
|
||||
const saveButton = page.locator('button:has-text("Save")')
|
||||
await expect(saveButton).toBeHidden()
|
||||
await expect(
|
||||
page.locator('input[type="email"]').getAttribute('disabled')
|
||||
).toBeDefined()
|
||||
await page.fill('#name', 'John Doe')
|
||||
expect(saveButton).toBeVisible()
|
||||
await page.setInputFiles(
|
||||
'input[type="file"]',
|
||||
path.join(__dirname, '../fixtures/avatar.jpg')
|
||||
)
|
||||
await expect(page.locator('img')).toHaveAttribute(
|
||||
'src',
|
||||
new RegExp(
|
||||
`https://s3.eu-west-3.amazonaws.com/typebot/users/${process.env.PLAYWRIGHT_USER_ID}/avatar`,
|
||||
'gm'
|
||||
)
|
||||
)
|
||||
await saveButton.click()
|
||||
await expect(saveButton).toBeHidden()
|
||||
})
|
||||
|
||||
test('should display valid plans', async ({ page }) => {
|
||||
await updateUser({ plan: Plan.FREE, stripeId: null })
|
||||
await page.goto('/account')
|
||||
await expect(page.locator('text=Free plan')).toBeVisible()
|
||||
await page.evaluate(refreshUser)
|
||||
await page.reload()
|
||||
const manageSubscriptionButton = page.locator(
|
||||
'a:has-text("Manage my subscription")'
|
||||
)
|
||||
await expect(manageSubscriptionButton).toBeHidden()
|
||||
await updateUser({ plan: Plan.PRO, stripeId: 'stripeId' })
|
||||
await page.reload()
|
||||
await expect(page.locator('text=Pro plan')).toBeVisible()
|
||||
await expect(manageSubscriptionButton).toBeVisible()
|
||||
})
|
||||
})
|
||||
@@ -30,7 +30,7 @@ test.describe('Results page', () => {
|
||||
await deleteButtonInConfirmDialog(page).click()
|
||||
await expect(page.locator('text=content199')).toBeHidden()
|
||||
await expect(page.locator('text=content198')).toBeHidden()
|
||||
await page.check(':nth-match(input[type="checkbox"], 1)', { force: true })
|
||||
await page.click('[data-testid="checkbox"] >> nth=0')
|
||||
await page.click('button:has-text("Delete198")')
|
||||
await deleteButtonInConfirmDialog(page).click()
|
||||
await expect(page.locator(':nth-match(tr, 2)')).toBeHidden()
|
||||
@@ -75,7 +75,7 @@ test.describe('Results page', () => {
|
||||
const { data } = parse(file)
|
||||
validateExportSelection(data)
|
||||
|
||||
await page.check(':nth-match(input[type="checkbox"], 1)', { force: true })
|
||||
await page.click('[data-testid="checkbox"] >> nth=0')
|
||||
const [downloadAll] = await Promise.all([
|
||||
page.waitForEvent('download'),
|
||||
page.locator('button:has-text("Export200")').click(),
|
||||
@@ -101,6 +101,6 @@ const validateExportAll = (data: unknown[]) => {
|
||||
}
|
||||
|
||||
const selectFirstResults = async (page: Page) => {
|
||||
await page.check(':nth-match(input[type="checkbox"], 2)', { force: true })
|
||||
return page.check(':nth-match(input[type="checkbox"], 3)', { force: true })
|
||||
await page.click('[data-testid="checkbox"] >> nth=1')
|
||||
return page.click('[data-testid="checkbox"] >> nth=2')
|
||||
}
|
||||
|
||||
338
apps/builder/public/mockServiceWorker.js
Normal file
338
apps/builder/public/mockServiceWorker.js
Normal file
@@ -0,0 +1,338 @@
|
||||
/* eslint-disable */
|
||||
/* tslint:disable */
|
||||
|
||||
/**
|
||||
* Mock Service Worker (0.36.8).
|
||||
* @see https://github.com/mswjs/msw
|
||||
* - Please do NOT modify this file.
|
||||
* - Please do NOT serve this file on production.
|
||||
*/
|
||||
|
||||
const INTEGRITY_CHECKSUM = '02f4ad4a2797f85668baf196e553d929'
|
||||
const bypassHeaderName = 'x-msw-bypass'
|
||||
const activeClientIds = new Set()
|
||||
|
||||
self.addEventListener('install', function () {
|
||||
return self.skipWaiting()
|
||||
})
|
||||
|
||||
self.addEventListener('activate', async function (event) {
|
||||
return self.clients.claim()
|
||||
})
|
||||
|
||||
self.addEventListener('message', async function (event) {
|
||||
const clientId = event.source.id
|
||||
|
||||
if (!clientId || !self.clients) {
|
||||
return
|
||||
}
|
||||
|
||||
const client = await self.clients.get(clientId)
|
||||
|
||||
if (!client) {
|
||||
return
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll()
|
||||
|
||||
switch (event.data) {
|
||||
case 'KEEPALIVE_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'KEEPALIVE_RESPONSE',
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'INTEGRITY_CHECK_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'INTEGRITY_CHECK_RESPONSE',
|
||||
payload: INTEGRITY_CHECKSUM,
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'MOCK_ACTIVATE': {
|
||||
activeClientIds.add(clientId)
|
||||
|
||||
sendToClient(client, {
|
||||
type: 'MOCKING_ENABLED',
|
||||
payload: true,
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'MOCK_DEACTIVATE': {
|
||||
activeClientIds.delete(clientId)
|
||||
break
|
||||
}
|
||||
|
||||
case 'CLIENT_CLOSED': {
|
||||
activeClientIds.delete(clientId)
|
||||
|
||||
const remainingClients = allClients.filter((client) => {
|
||||
return client.id !== clientId
|
||||
})
|
||||
|
||||
// Unregister itself when there are no more clients
|
||||
if (remainingClients.length === 0) {
|
||||
self.registration.unregister()
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Resolve the "main" client for the given event.
|
||||
// Client that issues a request doesn't necessarily equal the client
|
||||
// that registered the worker. It's with the latter the worker should
|
||||
// communicate with during the response resolving phase.
|
||||
async function resolveMainClient(event) {
|
||||
const client = await self.clients.get(event.clientId)
|
||||
|
||||
if (client.frameType === 'top-level') {
|
||||
return client
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll()
|
||||
|
||||
return allClients
|
||||
.filter((client) => {
|
||||
// Get only those clients that are currently visible.
|
||||
return client.visibilityState === 'visible'
|
||||
})
|
||||
.find((client) => {
|
||||
// Find the client ID that's recorded in the
|
||||
// set of clients that have registered the worker.
|
||||
return activeClientIds.has(client.id)
|
||||
})
|
||||
}
|
||||
|
||||
async function handleRequest(event, requestId) {
|
||||
const client = await resolveMainClient(event)
|
||||
const response = await getResponse(event, client, requestId)
|
||||
|
||||
// Send back the response clone for the "response:*" life-cycle events.
|
||||
// Ensure MSW is active and ready to handle the message, otherwise
|
||||
// this message will pend indefinitely.
|
||||
if (client && activeClientIds.has(client.id)) {
|
||||
;(async function () {
|
||||
const clonedResponse = response.clone()
|
||||
sendToClient(client, {
|
||||
type: 'RESPONSE',
|
||||
payload: {
|
||||
requestId,
|
||||
type: clonedResponse.type,
|
||||
ok: clonedResponse.ok,
|
||||
status: clonedResponse.status,
|
||||
statusText: clonedResponse.statusText,
|
||||
body:
|
||||
clonedResponse.body === null ? null : await clonedResponse.text(),
|
||||
headers: serializeHeaders(clonedResponse.headers),
|
||||
redirected: clonedResponse.redirected,
|
||||
},
|
||||
})
|
||||
})()
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
async function getResponse(event, client, requestId) {
|
||||
const { request } = event
|
||||
const requestClone = request.clone()
|
||||
const getOriginalResponse = () => fetch(requestClone)
|
||||
|
||||
// Bypass mocking when the request client is not active.
|
||||
if (!client) {
|
||||
return getOriginalResponse()
|
||||
}
|
||||
|
||||
// Bypass initial page load requests (i.e. static assets).
|
||||
// The absence of the immediate/parent client in the map of the active clients
|
||||
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
|
||||
// and is not ready to handle requests.
|
||||
if (!activeClientIds.has(client.id)) {
|
||||
return await getOriginalResponse()
|
||||
}
|
||||
|
||||
// Bypass requests with the explicit bypass header
|
||||
if (requestClone.headers.get(bypassHeaderName) === 'true') {
|
||||
const cleanRequestHeaders = serializeHeaders(requestClone.headers)
|
||||
|
||||
// Remove the bypass header to comply with the CORS preflight check.
|
||||
delete cleanRequestHeaders[bypassHeaderName]
|
||||
|
||||
const originalRequest = new Request(requestClone, {
|
||||
headers: new Headers(cleanRequestHeaders),
|
||||
})
|
||||
|
||||
return fetch(originalRequest)
|
||||
}
|
||||
|
||||
// Send the request to the client-side MSW.
|
||||
const reqHeaders = serializeHeaders(request.headers)
|
||||
const body = await request.text()
|
||||
|
||||
const clientMessage = await sendToClient(client, {
|
||||
type: 'REQUEST',
|
||||
payload: {
|
||||
id: requestId,
|
||||
url: request.url,
|
||||
method: request.method,
|
||||
headers: reqHeaders,
|
||||
cache: request.cache,
|
||||
mode: request.mode,
|
||||
credentials: request.credentials,
|
||||
destination: request.destination,
|
||||
integrity: request.integrity,
|
||||
redirect: request.redirect,
|
||||
referrer: request.referrer,
|
||||
referrerPolicy: request.referrerPolicy,
|
||||
body,
|
||||
bodyUsed: request.bodyUsed,
|
||||
keepalive: request.keepalive,
|
||||
},
|
||||
})
|
||||
|
||||
switch (clientMessage.type) {
|
||||
case 'MOCK_SUCCESS': {
|
||||
return delayPromise(
|
||||
() => respondWithMock(clientMessage),
|
||||
clientMessage.payload.delay,
|
||||
)
|
||||
}
|
||||
|
||||
case 'MOCK_NOT_FOUND': {
|
||||
return getOriginalResponse()
|
||||
}
|
||||
|
||||
case 'NETWORK_ERROR': {
|
||||
const { name, message } = clientMessage.payload
|
||||
const networkError = new Error(message)
|
||||
networkError.name = name
|
||||
|
||||
// Rejecting a request Promise emulates a network error.
|
||||
throw networkError
|
||||
}
|
||||
|
||||
case 'INTERNAL_ERROR': {
|
||||
const parsedBody = JSON.parse(clientMessage.payload.body)
|
||||
|
||||
console.error(
|
||||
`\
|
||||
[MSW] Uncaught exception in the request handler for "%s %s":
|
||||
|
||||
${parsedBody.location}
|
||||
|
||||
This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses\
|
||||
`,
|
||||
request.method,
|
||||
request.url,
|
||||
)
|
||||
|
||||
return respondWithMock(clientMessage)
|
||||
}
|
||||
}
|
||||
|
||||
return getOriginalResponse()
|
||||
}
|
||||
|
||||
self.addEventListener('fetch', function (event) {
|
||||
const { request } = event
|
||||
const accept = request.headers.get('accept') || ''
|
||||
|
||||
// Bypass server-sent events.
|
||||
if (accept.includes('text/event-stream')) {
|
||||
return
|
||||
}
|
||||
|
||||
// Bypass navigation requests.
|
||||
if (request.mode === 'navigate') {
|
||||
return
|
||||
}
|
||||
|
||||
// Opening the DevTools triggers the "only-if-cached" request
|
||||
// that cannot be handled by the worker. Bypass such requests.
|
||||
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
|
||||
return
|
||||
}
|
||||
|
||||
// Bypass all requests when there are no active clients.
|
||||
// Prevents the self-unregistered worked from handling requests
|
||||
// after it's been deleted (still remains active until the next reload).
|
||||
if (activeClientIds.size === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const requestId = uuidv4()
|
||||
|
||||
return event.respondWith(
|
||||
handleRequest(event, requestId).catch((error) => {
|
||||
if (error.name === 'NetworkError') {
|
||||
console.warn(
|
||||
'[MSW] Successfully emulated a network error for the "%s %s" request.',
|
||||
request.method,
|
||||
request.url,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// At this point, any exception indicates an issue with the original request/response.
|
||||
console.error(
|
||||
`\
|
||||
[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
|
||||
request.method,
|
||||
request.url,
|
||||
`${error.name}: ${error.message}`,
|
||||
)
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
function serializeHeaders(headers) {
|
||||
const reqHeaders = {}
|
||||
headers.forEach((value, name) => {
|
||||
reqHeaders[name] = reqHeaders[name]
|
||||
? [].concat(reqHeaders[name]).concat(value)
|
||||
: value
|
||||
})
|
||||
return reqHeaders
|
||||
}
|
||||
|
||||
function sendToClient(client, message) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const channel = new MessageChannel()
|
||||
|
||||
channel.port1.onmessage = (event) => {
|
||||
if (event.data && event.data.error) {
|
||||
return reject(event.data.error)
|
||||
}
|
||||
|
||||
resolve(event.data)
|
||||
}
|
||||
|
||||
client.postMessage(JSON.stringify(message), [channel.port2])
|
||||
})
|
||||
}
|
||||
|
||||
function delayPromise(cb, duration) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => resolve(cb()), duration)
|
||||
})
|
||||
}
|
||||
|
||||
function respondWithMock(clientMessage) {
|
||||
return new Response(clientMessage.payload.body, {
|
||||
...clientMessage.payload,
|
||||
headers: clientMessage.payload.headers,
|
||||
})
|
||||
}
|
||||
|
||||
function uuidv4() {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
||||
const r = (Math.random() * 16) | 0
|
||||
const v = c == 'x' ? r : (r & 0x3) | 0x8
|
||||
return v.toString(16)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user