2021-06-25 14:46:02 +02:00
|
|
|
module FetchMock {
|
|
|
|
const fetch = jest.requireActual("node-fetch")
|
2022-01-05 16:01:28 +01:00
|
|
|
let failCount = 0
|
2021-06-25 14:46:02 +02:00
|
|
|
|
|
|
|
module.exports = async (url: any, opts: any) => {
|
|
|
|
function json(body: any, status = 200) {
|
|
|
|
return {
|
|
|
|
status,
|
|
|
|
headers: {
|
2021-12-09 15:12:01 +01:00
|
|
|
raw: () => {
|
|
|
|
return { "content-type": ["application/json"] }
|
|
|
|
},
|
2021-06-25 14:46:02 +02:00
|
|
|
get: () => {
|
|
|
|
return ["application/json"]
|
|
|
|
},
|
|
|
|
},
|
|
|
|
json: async () => {
|
2022-09-28 09:56:45 +02:00
|
|
|
//x-www-form-encoded body is a URLSearchParams
|
|
|
|
//The call to stringify it leaves it blank
|
|
|
|
if (body?.opts?.body instanceof URLSearchParams) {
|
|
|
|
const paramArray = Array.from(body.opts.body.entries())
|
|
|
|
body.opts.body = paramArray.reduce((acc: any, pair: any) => {
|
|
|
|
acc[pair[0]] = pair[1]
|
|
|
|
return acc
|
|
|
|
}, {})
|
|
|
|
}
|
2021-06-25 14:46:02 +02:00
|
|
|
return body
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-05 10:59:08 +02:00
|
|
|
if (url.includes("/api/global")) {
|
2021-06-25 14:46:02 +02:00
|
|
|
return json({
|
|
|
|
email: "test@test.com",
|
|
|
|
_id: "us_test@test.com",
|
|
|
|
status: "active",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
// mocked data based on url
|
|
|
|
else if (url.includes("api/apps")) {
|
|
|
|
return json({
|
|
|
|
app1: {
|
|
|
|
url: "/app1",
|
|
|
|
},
|
|
|
|
})
|
|
|
|
} else if (url.includes("test.com")) {
|
|
|
|
return json({
|
|
|
|
body: opts.body,
|
|
|
|
url,
|
|
|
|
method: opts.method,
|
|
|
|
})
|
|
|
|
} else if (url.includes("invalid.com")) {
|
|
|
|
return json(
|
|
|
|
{
|
|
|
|
invalid: true,
|
|
|
|
},
|
|
|
|
404
|
|
|
|
)
|
|
|
|
} else if (url.includes("_search")) {
|
2022-09-28 09:56:45 +02:00
|
|
|
const body = opts.body
|
|
|
|
const parts = body.split("tableId:")
|
|
|
|
let tableId
|
|
|
|
if (parts && parts[1]) {
|
|
|
|
tableId = parts[1].split('"')[0]
|
|
|
|
}
|
2021-06-25 14:46:02 +02:00
|
|
|
return json({
|
|
|
|
rows: [
|
|
|
|
{
|
|
|
|
doc: {
|
|
|
|
_id: "test",
|
2022-09-28 09:56:45 +02:00
|
|
|
tableId: tableId,
|
|
|
|
query: opts.body,
|
2021-06-25 14:46:02 +02:00
|
|
|
},
|
|
|
|
},
|
|
|
|
],
|
|
|
|
bookmark: "test",
|
|
|
|
})
|
2022-01-04 19:23:45 +01:00
|
|
|
} else if (url.includes("google.com")) {
|
|
|
|
return json({
|
|
|
|
url,
|
|
|
|
opts,
|
2022-01-20 09:17:08 +01:00
|
|
|
value:
|
|
|
|
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-GB"></html>',
|
2022-01-04 19:23:45 +01:00
|
|
|
})
|
2022-01-05 16:01:28 +01:00
|
|
|
} else if (url.includes("failonce.com")) {
|
|
|
|
failCount++
|
|
|
|
if (failCount === 1) {
|
|
|
|
return json({ message: "error" }, 500)
|
|
|
|
} else {
|
|
|
|
return json({
|
|
|
|
fails: failCount - 1,
|
|
|
|
url,
|
|
|
|
opts,
|
|
|
|
})
|
|
|
|
}
|
2021-06-25 14:46:02 +02:00
|
|
|
}
|
|
|
|
return fetch(url, opts)
|
|
|
|
}
|
|
|
|
}
|