Skip to content

Commit

Permalink
test: WriteClient.fetchForeignAsset
Browse files Browse the repository at this point in the history
  • Loading branch information
lihbr committed Sep 5, 2024
1 parent 4bc610d commit 012f59f
Show file tree
Hide file tree
Showing 10 changed files with 304 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/WriteClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1002,7 +1002,7 @@ export class WriteClient<
const blob = await res.blob()

return new File([blob], "", {

Check failure on line 1004 in src/WriteClient.ts

View workflow job for this annotation

GitHub Actions / Suite (ubuntu-latest, Node 18)

test/writeClient-fetchForeignAsset.test.ts > fetches a foreign asset with content type

ReferenceError: File is not defined ❯ WriteClient.fetchForeignAsset src/WriteClient.ts:1004:3 ❯ test/writeClient-fetchForeignAsset.test.ts:23:15

Check failure on line 1004 in src/WriteClient.ts

View workflow job for this annotation

GitHub Actions / Suite (ubuntu-latest, Node 18)

test/writeClient-fetchForeignAsset.test.ts > fetches a foreign asset with no content type

ReferenceError: File is not defined ❯ WriteClient.fetchForeignAsset src/WriteClient.ts:1004:3 ❯ test/writeClient-fetchForeignAsset.test.ts:40:15

Check failure on line 1004 in src/WriteClient.ts

View workflow job for this annotation

GitHub Actions / Suite (ubuntu-latest, Node 18)

test/writeClient-fetchForeignAsset.test.ts > supports custom headers

ReferenceError: File is not defined ❯ WriteClient.fetchForeignAsset src/WriteClient.ts:1004:3 ❯ test/writeClient-fetchForeignAsset.test.ts:103:15

Check failure on line 1004 in src/WriteClient.ts

View workflow job for this annotation

GitHub Actions / Suite (ubuntu-latest, Node 18)

test/writeClient-fetchForeignAsset.test.ts > supports global custom headers

ReferenceError: File is not defined ❯ WriteClient.fetchForeignAsset src/WriteClient.ts:1004:3 ❯ test/writeClient-fetchForeignAsset.test.ts:129:15
type: res.headers.get("content-type") || "",
type: res.headers.get("content-type") || undefined,
})
}

Expand Down
33 changes: 32 additions & 1 deletion test/__testutils__/mockPrismicAssetAPI.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { type TestContext } from "vitest"

import type { RestRequest } from "msw"
import { rest } from "msw"

import type { WriteClient } from "../../src"
Expand All @@ -20,6 +21,7 @@ type MockPrismicAssetAPIArgs = {
ctx: TestContext
client: WriteClient
writeToken?: string
requiredHeaders?: Record<string, string>
getRequiredParams?: Record<string, string | string[]>
existingAssets?: Asset[][] | number[]
newAssets?: Asset[]
Expand Down Expand Up @@ -85,6 +87,16 @@ export const mockPrismicAssetAPI = (
}) || []
const tagsDatabase: AssetTag[] = args.existingTags || []

const validateHeaders = (req: RestRequest) => {
if (args.requiredHeaders) {
for (const name in args.requiredHeaders) {
const requiredValue = args.requiredHeaders[name]

args.ctx.expect(req.headers.get(name)).toBe(requiredValue)
}
}
}

args.ctx.server.use(
rest.get(`${assetAPIEndpoint}assets`, async (req, res, ctx) => {
if (
Expand All @@ -106,15 +118,25 @@ export const mockPrismicAssetAPI = (
}
}

validateHeaders(req)

const index = Number.parseInt(req.url.searchParams.get("cursor") ?? "0")
const items: Asset[] = assetsDatabase[index] || []

let missing_ids: string[] | undefined
const ids = req.url.searchParams.getAll("ids")
if (ids.length) {
missing_ids = ids.filter((id) =>
assetsDatabase.flat().find((item) => item.id === id),
)
}

const response: GetAssetsResult = {
total: items.length,
items,
is_opensearch_result: false,
cursor: assetsDatabase[index + 1] ? `${index + 1}` : undefined,
missing_ids: [],
missing_ids,
}

return res(ctx.json(response))
Expand All @@ -127,6 +149,8 @@ export const mockPrismicAssetAPI = (
return res(ctx.status(401), ctx.json({ error: "unauthorized" }))
}

validateHeaders(req)

const response: PostAssetResult =
args.newAssets?.shift() ?? mockAsset(args.ctx)

Expand All @@ -142,6 +166,9 @@ export const mockPrismicAssetAPI = (
) {
return res(ctx.status(401), ctx.json({ error: "unauthorized" }))
}

validateHeaders(req)

const { tags, ...body } = await req.json<PatchAssetParams>()

const asset = assetsDatabase
Expand Down Expand Up @@ -179,6 +206,8 @@ export const mockPrismicAssetAPI = (
return res(ctx.status(401), ctx.json({ error: "unauthorized" }))
}

validateHeaders(req)

const items: AssetTag[] = tagsDatabase

const response: GetAssetTagsResult = { items }
Expand All @@ -193,6 +222,8 @@ export const mockPrismicAssetAPI = (
return res(ctx.status(401), ctx.json({ error: "unauthorized" }))
}

validateHeaders(req)

const body = await req.json<PostAssetTagParams>()

const tag: AssetTag = {
Expand Down
16 changes: 16 additions & 0 deletions test/__testutils__/mockPrismicMigrationAPI.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { TestContext } from "vitest"

import type { RestRequest } from "msw"
import { rest } from "msw"

import type { PrismicDocument, WriteClient } from "../../src"
Expand All @@ -15,6 +16,7 @@ type MockPrismicMigrationAPIArgs = {
client: WriteClient
writeToken?: string
migrationAPIKey?: string
requiredHeaders?: Record<string, string>
existingDocuments?: (PostDocumentResult | PrismicDocument)[] | number
newDocuments?: { id: string; masterLanguageDocumentID?: string }[]
}
Expand All @@ -33,6 +35,16 @@ export const mockPrismicMigrationAPI = (

const documentsDatabase: Record<string, PostDocumentResult> = {}

const validateHeaders = (req: RestRequest) => {
if (args.requiredHeaders) {
for (const name in args.requiredHeaders) {
const requiredValue = args.requiredHeaders[name]

args.ctx.expect(req.headers.get(name)).toBe(requiredValue)
}
}
}

if (args.existingDocuments) {
if (typeof args.existingDocuments === "number") {
for (let i = 0; i < args.existingDocuments; i++) {
Expand Down Expand Up @@ -72,6 +84,8 @@ export const mockPrismicMigrationAPI = (
return res(ctx.status(403), ctx.json({ Message: "forbidden" }))
}

validateHeaders(req)

const body = await req.json<PostDocumentParams>()

const newDocument = args.newDocuments?.shift()
Expand Down Expand Up @@ -105,6 +119,8 @@ export const mockPrismicMigrationAPI = (
return res(ctx.status(403), ctx.json({ Message: "forbidden" }))
}

validateHeaders(req)

const document = documentsDatabase[req.params.id as string]

if (!document) {
Expand Down
18 changes: 17 additions & 1 deletion test/writeClient-createAsset.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ it.concurrent("throws forbidden error on invalid credentials", async (ctx) => {

// It seems like p-limit and node-fetch are not happy friends :/
// https://github.com/sindresorhus/p-limit/issues/64
it.skip("supports abort controller", async (ctx) => {
it.skip("is abortable with an AbortController", async (ctx) => {
const client = createTestWriteClient({ ctx })

const controller = new AbortController()
Expand All @@ -208,6 +208,22 @@ it.skip("supports abort controller", async (ctx) => {
).rejects.toThrow(/aborted/i)
})

it.concurrent("supports custom headers", async (ctx) => {
const client = createTestWriteClient({ ctx })

const headers = { "x-custom": "foo" }

mockPrismicAssetAPI({ ctx, client, requiredHeaders: headers })

// @ts-expect-error - testing purposes
const asset = await client.createAsset("file", "foo.jpg", {
fetchOptions: { headers },
})

ctx.expect(asset.id).toBeTypeOf("string")
ctx.expect.assertions(2)
})

it.concurrent("respects unknown rate limit", async (ctx) => {
const client = createTestWriteClient({ ctx })

Expand Down
30 changes: 29 additions & 1 deletion test/writeClient-createAssetTag.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ it.concurrent("throws forbidden error on invalid credentials", async (ctx) => {

// It seems like p-limit and node-fetch are not happy friends :/
// https://github.com/sindresorhus/p-limit/issues/64
it.skip("supports abort controller", async (ctx) => {
it.skip("is abortable with an AbortController", async (ctx) => {
const client = createTestWriteClient({ ctx })

const controller = new AbortController()
Expand All @@ -83,6 +83,34 @@ it.skip("supports abort controller", async (ctx) => {
).rejects.toThrow(/aborted/i)
})

it.concurrent("supports custom headers", async (ctx) => {
const client = createTestWriteClient({ ctx })

const headers = { "x-custom": "foo" }

const newTag: AssetTag = {
id: "00000000-4444-4444-4444-121212121212",
name: "foo",
created_at: 0,
last_modified: 0,
}

mockPrismicAssetAPI({
ctx,
client,
requiredHeaders: headers,
newTags: [newTag],
})

// @ts-expect-error - testing purposes
const tag = await client.createAssetTag(newTag.name, {
fetchOptions: { headers },
})

ctx.expect(tag).toStrictEqual(newTag)
ctx.expect.assertions(2)
})

it.concurrent("respects unknown rate limit", async (ctx) => {
const client = createTestWriteClient({ ctx })

Expand Down
31 changes: 30 additions & 1 deletion test/writeClient-createDocument.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ it.concurrent("throws forbidden error on invalid credentials", async (ctx) => {

// It seems like p-limit and node-fetch are not happy friends :/
// https://github.com/sindresorhus/p-limit/issues/64
it.skip("supports abort controller", async (ctx) => {
it.skip("is abortable with an AbortController", async (ctx) => {
const client = createTestWriteClient({ ctx })

const controller = new AbortController()
Expand All @@ -71,6 +71,35 @@ it.skip("supports abort controller", async (ctx) => {
).rejects.toThrow(/aborted/i)
})

it.concurrent("supports custom headers", async (ctx) => {
const client = createTestWriteClient({ ctx })

const headers = { "x-custom": "foo" }
const newDocument = { id: "foo" }

mockPrismicMigrationAPI({
ctx,
client,
requiredHeaders: headers,
newDocuments: [newDocument],
})

// @ts-expect-error - testing purposes
const { id } = await client.createDocument(
{
type: "type",
uid: "uid",
lang: "lang",
data: {},
},
"Foo",
{ fetchOptions: { headers } },
)

ctx.expect(id).toBe(newDocument.id)
ctx.expect.assertions(2)
})

it.concurrent("respects unknown rate limit", async (ctx) => {
const client = createTestWriteClient({ ctx })

Expand Down
Loading

0 comments on commit 012f59f

Please sign in to comment.