chore: replace all __dirname's in test dir

This commit is contained in:
Alessio Gravili
2024-03-08 11:09:59 -05:00
parent 45a443989a
commit 881d1e9594
36 changed files with 230 additions and 123 deletions

View File

@@ -1,4 +1,4 @@
import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types' import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types.js'
export const mediaSlug = 'media' export const mediaSlug = 'media'

View File

@@ -1,4 +1,4 @@
import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types.d.ts' import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types.js'
import { mediaSlug } from '../Media/index.js' import { mediaSlug } from '../Media/index.js'
@@ -51,6 +51,5 @@ export const PostsCollection: CollectionConfig = {
], ],
}, },
], ],
versions: true,
slug: postsSlug, slug: postsSlug,
} }

View File

@@ -1,4 +1,4 @@
import type { GlobalConfig } from '../../../../packages/payload/src/globals/config/types' import type { GlobalConfig } from '../../../../packages/payload/src/globals/config/types.js'
export const menuSlug = 'menu' export const menuSlug = 'menu'

View File

@@ -1,21 +1,22 @@
import type { FieldAccess } from '../../packages/payload/src/fields/config/types' import type { FieldAccess } from '../../packages/payload/src/fields/config/types.js'
import { buildConfigWithDefaults } from '../buildConfigWithDefaults' import { buildConfigWithDefaults } from '../buildConfigWithDefaults.js'
import { devUser } from '../credentials' import { devUser } from '../credentials.js'
import { firstArrayText, secondArrayText } from './shared'
import { import {
docLevelAccessSlug, docLevelAccessSlug,
firstArrayText,
hiddenAccessSlug, hiddenAccessSlug,
hiddenFieldsSlug, hiddenFieldsSlug,
readOnlySlug, readOnlySlug,
relyOnRequestHeadersSlug, relyOnRequestHeadersSlug,
restrictedSlug, restrictedSlug,
restrictedVersionsSlug, restrictedVersionsSlug,
secondArrayText,
siblingDataSlug, siblingDataSlug,
slug, slug,
unrestrictedSlug, unrestrictedSlug,
userRestrictedSlug, userRestrictedSlug,
} from './shared' } from './shared.js'
const openAccess = { const openAccess = {
create: () => true, create: () => true,

View File

@@ -2,6 +2,7 @@ import type { Page } from '@playwright/test'
import type { Payload } from 'payload' import type { Payload } from 'payload'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import { fileURLToPath } from 'url'
import type { ReadOnlyCollection, RestrictedVersion } from './payload-types' import type { ReadOnlyCollection, RestrictedVersion } from './payload-types'
@@ -18,6 +19,8 @@ import {
slug, slug,
unrestrictedSlug, unrestrictedSlug,
} from './shared' } from './shared'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
/** /**
* TODO: Access Control * TODO: Access Control
@@ -39,7 +42,7 @@ describe('access control', () => {
let serverURL: string let serverURL: string
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ payload, serverURL } = await initPayloadE2E({ config, dirname: __dirname })) ;({ payload, serverURL } = await initPayloadE2E({ config, dirname }))
url = new AdminUrlUtil(serverURL, slug) url = new AdminUrlUtil(serverURL, slug)
restrictedUrl = new AdminUrlUtil(serverURL, restrictedSlug) restrictedUrl = new AdminUrlUtil(serverURL, restrictedSlug)

View File

@@ -36,6 +36,8 @@ import {
slugPluralLabel, slugPluralLabel,
} from './shared' } from './shared'
import { import {
customIdCollectionId,
customIdCollectionSlug,
customViews2CollectionSlug, customViews2CollectionSlug,
geoCollectionSlug, geoCollectionSlug,
globalSlug, globalSlug,
@@ -44,8 +46,6 @@ import {
noApiViewCollectionSlug, noApiViewCollectionSlug,
noApiViewGlobalSlug, noApiViewGlobalSlug,
postsCollectionSlug, postsCollectionSlug,
customIdCollectionSlug,
customIdCollectionId,
} from './slugs' } from './slugs'
const { beforeAll, beforeEach, describe } = test const { beforeAll, beforeEach, describe } = test
@@ -55,6 +55,11 @@ const description = 'Description'
let payload: Payload let payload: Payload
import path from 'path'
import { fileURLToPath } from 'url'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
describe('admin', () => { describe('admin', () => {
let page: Page let page: Page
let geoUrl: AdminUrlUtil let geoUrl: AdminUrlUtil
@@ -63,7 +68,7 @@ describe('admin', () => {
let serverURL: string let serverURL: string
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ payload, serverURL } = await initPayloadE2E({ config, dirname: __dirname })) ;({ payload, serverURL } = await initPayloadE2E({ config, dirname }))
geoUrl = new AdminUrlUtil(serverURL, geoCollectionSlug) geoUrl = new AdminUrlUtil(serverURL, geoCollectionSlug)
url = new AdminUrlUtil(serverURL, postsCollectionSlug) url = new AdminUrlUtil(serverURL, postsCollectionSlug)
customViewsURL = new AdminUrlUtil(serverURL, customViews2CollectionSlug) customViewsURL = new AdminUrlUtil(serverURL, customViews2CollectionSlug)
@@ -537,7 +542,7 @@ describe('admin', () => {
test('should allow custom ID field nested inside an unnamed tab', async () => { test('should allow custom ID field nested inside an unnamed tab', async () => {
await page.goto(url.collection('customIdTab') + '/' + customIdCollectionId) await page.goto(url.collection('customIdTab') + '/' + customIdCollectionId)
const idField = await page.locator('#field-id') const idField = page.locator('#field-id')
await expect(idField).toHaveValue(customIdCollectionId) await expect(idField).toHaveValue(customIdCollectionId)
}) })
@@ -545,7 +550,7 @@ describe('admin', () => {
test('should allow custom ID field nested inside a row', async () => { test('should allow custom ID field nested inside a row', async () => {
await page.goto(url.collection('customIdRow') + '/' + customIdCollectionId) await page.goto(url.collection('customIdRow') + '/' + customIdCollectionId)
const idField = await page.locator('#field-id') const idField = page.locator('#field-id')
await expect(idField).toHaveValue(customIdCollectionId) await expect(idField).toHaveValue(customIdCollectionId)
}) })

View File

@@ -1,6 +1,8 @@
import type { Page } from '@playwright/test' import type { Page } from '@playwright/test'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import path from 'path'
import { fileURLToPath } from 'url'
import payload from '../../packages/payload/src' import payload from '../../packages/payload/src'
import { initPageConsoleErrorCatch, login, saveDocAndAssert } from '../helpers' import { initPageConsoleErrorCatch, login, saveDocAndAssert } from '../helpers'
@@ -8,6 +10,8 @@ import { AdminUrlUtil } from '../helpers/adminUrlUtil'
import { initPayloadE2E } from '../helpers/configHelpers' import { initPayloadE2E } from '../helpers/configHelpers'
import config from './config' import config from './config'
import { apiKeysSlug, slug } from './shared' import { apiKeysSlug, slug } from './shared'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
/** /**
* TODO: Auth * TODO: Auth
@@ -29,7 +33,7 @@ describe('auth', () => {
let apiURL: string let apiURL: string
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ serverURL } = await initPayloadE2E({ config, dirname: __dirname })) ;({ serverURL } = await initPayloadE2E({ config, dirname }))
url = new AdminUrlUtil(serverURL, slug) url = new AdminUrlUtil(serverURL, slug)
const context = await browser.newContext() const context = await browser.newContext()

View File

@@ -1,9 +1,12 @@
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { CollectionConfig } from '../../packages/payload/src/collections/config/types' import type { CollectionConfig } from '../../packages/payload/src/collections/config/types'
import { buildConfigWithDefaults } from '../buildConfigWithDefaults' import { buildConfigWithDefaults } from '../buildConfigWithDefaults'
import { devUser } from '../credentials' import { devUser } from '../credentials'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
export interface Relation { export interface Relation {
id: string id: string
@@ -355,7 +358,7 @@ export default buildConfigWithDefaults({
}, },
} }
}, },
schemaOutputFile: path.resolve(__dirname, 'schema.graphql'), schemaOutputFile: path.resolve(dirname, 'schema.graphql'),
}, },
onInit: async (payload) => { onInit: async (payload) => {
await payload.create({ await payload.create({

View File

@@ -4,9 +4,13 @@ import * as CommentJson from 'comment-json'
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
import shelljs from 'shelljs' import shelljs from 'shelljs'
import { fileURLToPath } from 'url'
import { promisify } from 'util' import { promisify } from 'util'
import { initNext } from '../../packages/create-payload-app/src/lib/init-next' import { initNext } from '../../packages/create-payload-app/src/lib/init-next'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const readFile = promisify(fs.readFile) const readFile = promisify(fs.readFile)
const nextCreateCommands: Partial<Record<'noSrcDir' | 'srcDir', string>> = { const nextCreateCommands: Partial<Record<'noSrcDir' | 'srcDir', string>> = {
@@ -24,16 +28,13 @@ describe('create-payload-app', () => {
describe('Next.js app template files', () => { describe('Next.js app template files', () => {
it('should exist in dist', () => { it('should exist in dist', () => {
const distPath = path.resolve( const distPath = path.resolve(dirname, '../../packages/create-payload-app/dist/app/(payload)')
__dirname,
'../../packages/create-payload-app/dist/app/(payload)',
)
expect(fs.existsSync(distPath)).toBe(true) expect(fs.existsSync(distPath)).toBe(true)
}) })
}) })
describe.each(Object.keys(nextCreateCommands))(`--init-next with %s`, (nextCmdKey) => { describe.each(Object.keys(nextCreateCommands))(`--init-next with %s`, (nextCmdKey) => {
const projectDir = path.resolve(__dirname, 'test-app') const projectDir = path.resolve(dirname, 'test-app')
beforeEach(() => { beforeEach(() => {
if (fs.existsSync(projectDir)) { if (fs.existsSync(projectDir)) {

View File

@@ -1,5 +1,6 @@
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { PostgresAdapter } from '../../packages/db-postgres/src/types' import type { PostgresAdapter } from '../../packages/db-postgres/src/types'
import type { Payload } from '../../packages/payload/src' import type { Payload } from '../../packages/payload/src'
@@ -13,18 +14,20 @@ import { devUser } from '../credentials'
import removeFiles from '../helpers/removeFiles' import removeFiles from '../helpers/removeFiles'
import { startMemoryDB } from '../startMemoryDB' import { startMemoryDB } from '../startMemoryDB'
import configPromise from './config' import configPromise from './config'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
let payload: Payload let payload: Payload
let user: TypeWithID & Record<string, unknown> let user: TypeWithID & Record<string, unknown>
const collection = 'posts' const collection = 'posts'
const title = 'title' const title = 'title'
process.env.PAYLOAD_CONFIG_PATH = path.join(__dirname, 'config.ts') process.env.PAYLOAD_CONFIG_PATH = path.join(dirname, 'config.ts')
describe('database', () => { describe('database', () => {
beforeAll(async () => { beforeAll(async () => {
const config = await startMemoryDB(configPromise) const config = await startMemoryDB(configPromise)
payload = await getPayload({ config }) payload = await getPayload({ config })
payload.db.migrationDir = path.join(__dirname, './migrations') payload.db.migrationDir = path.join(dirname, './migrations')
const loginResult = await payload.login({ const loginResult = await payload.login({
collection: 'users', collection: 'users',
@@ -51,7 +54,7 @@ describe('database', () => {
}) })
afterAll(() => { afterAll(() => {
removeFiles(path.join(__dirname, './migrations')) removeFiles(path.join(dirname, './migrations'))
}) })
it('should run migrate:create', async () => { it('should run migrate:create', async () => {

View File

@@ -8,12 +8,17 @@ import config from './config'
const { beforeAll, describe } = test const { beforeAll, describe } = test
import path from 'path'
import { fileURLToPath } from 'url'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
describe('field error states', () => { describe('field error states', () => {
let serverURL: string let serverURL: string
let page: Page let page: Page
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ serverURL } = await initPayloadE2E({ config, dirname: __dirname })) ;({ serverURL } = await initPayloadE2E({ config, dirname }))
const context = await browser.newContext() const context = await browser.newContext()
page = await context.newPage() page = await context.newPage()
initPageConsoleErrorCatch(page) initPageConsoleErrorCatch(page)

View File

@@ -1,6 +1,8 @@
import type { Page } from '@playwright/test' import type { Page } from '@playwright/test'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import path from 'path'
import { fileURLToPath } from 'url'
import type { Payload } from '../../packages/payload/src' import type { Payload } from '../../packages/payload/src'
import type { import type {
@@ -26,6 +28,8 @@ import {
slug, slug,
} from './collectionSlugs' } from './collectionSlugs'
import config from './config' import config from './config'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const { beforeAll, beforeEach, describe } = test const { beforeAll, beforeEach, describe } = test
@@ -44,7 +48,7 @@ describe('fields - relationship', () => {
let serverURL: string let serverURL: string
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ payload, serverURL } = await initPayloadE2E({ config, dirname: __dirname })) ;({ payload, serverURL } = await initPayloadE2E({ config, dirname }))
url = new AdminUrlUtil(serverURL, slug) url = new AdminUrlUtil(serverURL, slug)

View File

@@ -1,13 +1,16 @@
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types' import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types'
import { uploadsSlug } from '../../slugs' import { uploadsSlug } from '../../slugs'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const Uploads: CollectionConfig = { const Uploads: CollectionConfig = {
slug: uploadsSlug, slug: uploadsSlug,
upload: { upload: {
staticDir: path.resolve(__dirname, './uploads'), staticDir: path.resolve(dirname, './uploads'),
}, },
fields: [ fields: [
{ {

View File

@@ -1,13 +1,16 @@
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types' import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types'
import { uploads2Slug } from '../../slugs' import { uploads2Slug } from '../../slugs'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const Uploads2: CollectionConfig = { const Uploads2: CollectionConfig = {
slug: uploads2Slug, slug: uploads2Slug,
upload: { upload: {
staticDir: path.resolve(__dirname, './uploads2'), staticDir: path.resolve(dirname, './uploads2'),
}, },
labels: { labels: {
singular: 'Upload 2', singular: 'Upload 2',

View File

@@ -1,13 +1,16 @@
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types' import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types'
import { uploads3Slug } from '../../slugs' import { uploads3Slug } from '../../slugs'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const Uploads3: CollectionConfig = { const Uploads3: CollectionConfig = {
slug: uploads3Slug, slug: uploads3Slug,
upload: { upload: {
staticDir: path.resolve(__dirname, './uploads3'), staticDir: path.resolve(dirname, './uploads3'),
}, },
labels: { labels: {
singular: 'Upload 3', singular: 'Upload 3',

View File

@@ -3,6 +3,7 @@ import type { Payload } from 'payload'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { RelationshipField, TextField } from './payload-types' import type { RelationshipField, TextField } from './payload-types'
@@ -28,6 +29,8 @@ import {
tabsFieldsSlug, tabsFieldsSlug,
textFieldsSlug, textFieldsSlug,
} from './slugs' } from './slugs'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const { afterEach, beforeAll, beforeEach, describe } = test const { afterEach, beforeAll, beforeEach, describe } = test
@@ -39,7 +42,7 @@ let serverURL: string
describe('fields', () => { describe('fields', () => {
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ payload, serverURL } = await initPayloadE2E({ config, dirname: __dirname })) ;({ payload, serverURL } = await initPayloadE2E({ config, dirname }))
client = new RESTClient(null, { defaultSlug: 'users', serverURL }) client = new RESTClient(null, { defaultSlug: 'users', serverURL })
await client.login() await client.login()
@@ -1845,7 +1848,7 @@ describe('fields', () => {
// create a jpg upload // create a jpg upload
await page await page
.locator('.file-field__upload input[type="file"]') .locator('.file-field__upload input[type="file"]')
.setInputFiles(path.resolve(__dirname, './collections/Upload/payload.jpg')) .setInputFiles(path.resolve(dirname, './collections/Upload/payload.jpg'))
await expect(page.locator('.file-field .file-field__filename')).toHaveValue('payload.jpg') await expect(page.locator('.file-field .file-field__filename')).toHaveValue('payload.jpg')
await page.locator('#action-save').click() await page.locator('#action-save').click()
await wait(200) await wait(200)
@@ -1871,7 +1874,7 @@ describe('fields', () => {
await page.locator('.field-type.upload .upload__toggler.doc-drawer__toggler').click() await page.locator('.field-type.upload .upload__toggler.doc-drawer__toggler').click()
await page await page
.locator('[id^=doc-drawer_uploads_1_] .file-field__upload input[type="file"]') .locator('[id^=doc-drawer_uploads_1_] .file-field__upload input[type="file"]')
.setInputFiles(path.resolve(__dirname, './uploads/payload.png')) .setInputFiles(path.resolve(dirname, './uploads/payload.png'))
await page.locator('[id^=doc-drawer_uploads_1_] #action-save').click() await page.locator('[id^=doc-drawer_uploads_1_] #action-save').click()
await wait(200) await wait(200)
await expect(page.locator('.Toastify')).toContainText('successfully') await expect(page.locator('.Toastify')).toContainText('successfully')
@@ -1897,7 +1900,7 @@ describe('fields', () => {
await page.locator('.field-type.upload .upload__toggler.doc-drawer__toggler').click() await page.locator('.field-type.upload .upload__toggler.doc-drawer__toggler').click()
await page await page
.locator('[id^=doc-drawer_uploads_1_] .file-field__upload input[type="file"]') .locator('[id^=doc-drawer_uploads_1_] .file-field__upload input[type="file"]')
.setInputFiles(path.resolve(__dirname, './uploads/payload.png')) .setInputFiles(path.resolve(dirname, './uploads/payload.png'))
await page.locator('[id^=doc-drawer_uploads_1_] #action-save').click() await page.locator('[id^=doc-drawer_uploads_1_] #action-save').click()
await wait(200) await wait(200)
await expect(page.locator('.Toastify')).toContainText('successfully') await expect(page.locator('.Toastify')).toContainText('successfully')
@@ -1920,7 +1923,7 @@ describe('fields', () => {
// create file in uploads 3 collection // create file in uploads 3 collection
await page await page
.locator('.file-field__upload input[type="file"]') .locator('.file-field__upload input[type="file"]')
.setInputFiles(path.resolve(__dirname, './collections/Upload/payload.jpg')) .setInputFiles(path.resolve(dirname, './collections/Upload/payload.jpg'))
await expect(page.locator('.file-field .file-field__filename')).toContainText('payload.jpg') await expect(page.locator('.file-field .file-field__filename')).toContainText('payload.jpg')
await page.locator('#action-save').click() await page.locator('#action-save').click()

View File

@@ -2,6 +2,8 @@ import type { Page } from '@playwright/test'
import type { SerializedEditorState, SerializedParagraphNode, SerializedTextNode } from 'lexical' import type { SerializedEditorState, SerializedParagraphNode, SerializedTextNode } from 'lexical'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import path from 'path'
import { fileURLToPath } from 'url'
import type { Payload } from '../../packages/payload/src' import type { Payload } from '../../packages/payload/src'
import type { SerializedBlockNode } from '../../packages/richtext-lexical/src' import type { SerializedBlockNode } from '../../packages/richtext-lexical/src'
@@ -15,6 +17,8 @@ import { lexicalDocData } from './collections/Lexical/data'
import config from './config' import config from './config'
import { clearAndSeedEverything } from './seed' import { clearAndSeedEverything } from './seed'
import { lexicalFieldsSlug } from './slugs' import { lexicalFieldsSlug } from './slugs'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const { beforeAll, describe, beforeEach } = test const { beforeAll, describe, beforeEach } = test
@@ -37,7 +41,7 @@ async function navigateToLexicalFields() {
describe('lexical', () => { describe('lexical', () => {
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ payload, serverURL } = await initPayloadE2E({ config, dirname: __dirname })) ;({ payload, serverURL } = await initPayloadE2E({ config, dirname }))
client = new RESTClient(null, { serverURL, defaultSlug: 'rich-text-fields' }) client = new RESTClient(null, { serverURL, defaultSlug: 'rich-text-fields' })
await client.login() await client.login()

View File

@@ -1,4 +1,5 @@
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import { type Payload } from '../../packages/payload/src' import { type Payload } from '../../packages/payload/src'
import getFileByPath from '../../packages/payload/src/uploads/getFileByPath' import getFileByPath from '../../packages/payload/src/uploads/getFileByPath'
@@ -44,6 +45,8 @@ import {
uploadsSlug, uploadsSlug,
usersSlug, usersSlug,
} from './slugs' } from './slugs'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
export async function clearAndSeedEverything(_payload: Payload) { export async function clearAndSeedEverything(_payload: Payload) {
return await seedDB({ return await seedDB({
@@ -172,6 +175,6 @@ export async function clearAndSeedEverything(_payload: Payload) {
}, },
shouldResetDB: true, shouldResetDB: true,
snapshotKey: 'fieldsTest', snapshotKey: 'fieldsTest',
uploadsDir: path.resolve(__dirname, './collections/Upload/uploads'), uploadsDir: path.resolve(dirname, './collections/Upload/uploads'),
}) })
} }

View File

@@ -6,16 +6,20 @@ import { setTestEnvPaths } from './helpers/setTestEnvPaths'
const [testConfigDir] = process.argv.slice(2) const [testConfigDir] = process.argv.slice(2)
import { fileURLToPath } from 'url'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
let testDir let testDir
if (testConfigDir) { if (testConfigDir) {
testDir = path.resolve(__dirname, testConfigDir) testDir = path.resolve(dirname, testConfigDir)
setTestEnvPaths(testDir) setTestEnvPaths(testDir)
generateGraphQLSchema() generateGraphQLSchema()
} else { } else {
// Generate graphql schema for entire directory // Generate graphql schema for entire directory
testDir = __dirname testDir = dirname
fs.readdirSync(__dirname, { withFileTypes: true }) fs.readdirSync(dirname, { withFileTypes: true })
.filter((f) => f.isDirectory()) .filter((f) => f.isDirectory())
.forEach((dir) => { .forEach((dir) => {
const suiteDir = path.resolve(testDir, dir.name) const suiteDir = path.resolve(testDir, dir.name)

View File

@@ -6,16 +6,20 @@ import { setTestEnvPaths } from './helpers/setTestEnvPaths'
const [testConfigDir] = process.argv.slice(2) const [testConfigDir] = process.argv.slice(2)
import { fileURLToPath } from 'url'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
let testDir let testDir
if (testConfigDir) { if (testConfigDir) {
testDir = path.resolve(__dirname, testConfigDir) testDir = path.resolve(dirname, testConfigDir)
setTestEnvPaths(testDir) setTestEnvPaths(testDir)
generateTypes() generateTypes()
} else { } else {
// Generate types for entire directory // Generate types for entire directory
testDir = __dirname testDir = dirname
fs.readdirSync(__dirname, { withFileTypes: true }) fs.readdirSync(dirname, { withFileTypes: true })
.filter((f) => f.isDirectory()) .filter((f) => f.isDirectory())
.forEach((dir) => { .forEach((dir) => {
const suiteDir = path.resolve(testDir, dir.name) const suiteDir = path.resolve(testDir, dir.name)

View File

@@ -1,13 +1,16 @@
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import { buildConfigWithDefaults } from '../buildConfigWithDefaults' import { buildConfigWithDefaults } from '../buildConfigWithDefaults'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
export default buildConfigWithDefaults({ export default buildConfigWithDefaults({
graphQL: { graphQL: {
schemaOutputFile: path.resolve(__dirname, 'schema.graphql'), schemaOutputFile: path.resolve(dirname, 'schema.graphql'),
}, },
typescript: { typescript: {
outputFile: path.resolve(__dirname, 'schema.ts'), outputFile: path.resolve(dirname, 'schema.ts'),
}, },
collections: [ collections: [
{ {

View File

@@ -2,6 +2,8 @@ import type { Page } from '@playwright/test'
import type { Payload } from 'payload' import type { Payload } from 'payload'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import path from 'path'
import { fileURLToPath } from 'url'
import { exactText, initPageConsoleErrorCatch, saveDocAndAssert } from '../helpers' import { exactText, initPageConsoleErrorCatch, saveDocAndAssert } from '../helpers'
import { AdminUrlUtil } from '../helpers/adminUrlUtil' import { AdminUrlUtil } from '../helpers/adminUrlUtil'
@@ -9,6 +11,8 @@ import { initPayloadE2E } from '../helpers/configHelpers'
import config from './config' import config from './config'
import { mobileBreakpoint } from './shared' import { mobileBreakpoint } from './shared'
import { startLivePreviewDemo } from './startLivePreviewDemo' import { startLivePreviewDemo } from './startLivePreviewDemo'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const { beforeAll, describe } = test const { beforeAll, describe } = test
@@ -38,7 +42,7 @@ describe('Live Preview', () => {
} }
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ serverURL, payload } = await initPayloadE2E({ config, dirname: __dirname })) ;({ serverURL, payload } = await initPayloadE2E({ config, dirname }))
url = new AdminUrlUtil(serverURL, 'pages') url = new AdminUrlUtil(serverURL, 'pages')
const context = await browser.newContext() const context = await browser.newContext()
page = await context.newPage() page = await context.newPage()

View File

@@ -1,4 +1,5 @@
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { Payload } from '../../packages/payload/src' import type { Payload } from '../../packages/payload/src'
import type { Media, Page, Post, Tenant } from './payload-types' import type { Media, Page, Post, Tenant } from './payload-types'
@@ -15,6 +16,8 @@ import { Pages } from './collections/Pages'
import { postsSlug } from './collections/Posts' import { postsSlug } from './collections/Posts'
import configPromise from './config' import configPromise from './config'
import { tenantsSlug } from './shared' import { tenantsSlug } from './shared'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const schemaJSON = fieldSchemaToJSON(Pages.fields) const schemaJSON = fieldSchemaToJSON(Pages.fields)
@@ -55,7 +58,7 @@ describe('Collections - Live Preview', () => {
}) })
// Create image // Create image
const filePath = path.resolve(__dirname, './seed/image-1.jpg') const filePath = path.resolve(dirname, './seed/image-1.jpg')
const file = await getFileByPath(filePath) const file = await getFileByPath(filePath)
file.name = 'image-1.jpg' file.name = 'image-1.jpg'

View File

@@ -1,4 +1,5 @@
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { Config } from '../../../packages/payload/src/config/types' import type { Config } from '../../../packages/payload/src/config/types'
@@ -15,9 +16,11 @@ import { post3 } from './post-3'
import { postsPage } from './posts-page' import { postsPage } from './posts-page'
import { tenant1 } from './tenant-1' import { tenant1 } from './tenant-1'
import { tenant2 } from './tenant-2' import { tenant2 } from './tenant-2'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
export const seed: Config['onInit'] = async (payload) => { export const seed: Config['onInit'] = async (payload) => {
const uploadsDir = path.resolve(__dirname, './media') const uploadsDir = path.resolve(dirname, './media')
removeFiles(path.normalize(uploadsDir)) removeFiles(path.normalize(uploadsDir))
await payload.create({ await payload.create({
@@ -41,7 +44,7 @@ export const seed: Config['onInit'] = async (payload) => {
const media = await payload.create({ const media = await payload.create({
collection: 'media', collection: 'media',
filePath: path.resolve(__dirname, 'image-1.jpg'), filePath: path.resolve(dirname, 'image-1.jpg'),
data: { data: {
alt: 'Image 1', alt: 'Image 1',
}, },

View File

@@ -1,7 +1,10 @@
import { spawn } from 'child_process' import { spawn } from 'child_process'
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { Payload } from '../../packages/payload/src' import type { Payload } from '../../packages/payload/src'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const installNodeModules = async (args: { payload: Payload }): Promise<void> => { const installNodeModules = async (args: { payload: Payload }): Promise<void> => {
const { payload } = args const { payload } = args
@@ -11,7 +14,7 @@ const installNodeModules = async (args: { payload: Payload }): Promise<void> =>
return new Promise(function (resolve) { return new Promise(function (resolve) {
// Install the node modules for the Next.js app // Install the node modules for the Next.js app
const installation = spawn('yarn', ['install'], { const installation = spawn('yarn', ['install'], {
cwd: path.resolve(__dirname, './next-app'), cwd: path.resolve(dirname, './next-app'),
}) })
installation.stdout.on('data', (data) => { installation.stdout.on('data', (data) => {
@@ -42,7 +45,7 @@ const bootNextApp = async (args: { payload: Payload }): Promise<void> => {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
// Boot up the Next.js app // Boot up the Next.js app
const app = spawn('yarn', ['dev'], { const app = spawn('yarn', ['dev'], {
cwd: path.resolve(__dirname, './next-app'), cwd: path.resolve(dirname, './next-app'),
}) })
app.stdout.on('data', (data) => { app.stdout.on('data', (data) => {

View File

@@ -2,6 +2,8 @@ import type { Page } from '@playwright/test'
import type { Payload } from 'payload' import type { Payload } from 'payload'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import path from 'path'
import { fileURLToPath } from 'url'
import type { LocalizedPost } from './payload-types' import type { LocalizedPost } from './payload-types'
@@ -21,6 +23,8 @@ import {
spanishLocale, spanishLocale,
withRequiredLocalizedFields, withRequiredLocalizedFields,
} from './shared' } from './shared'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
/** /**
* TODO: Localization * TODO: Localization
@@ -49,7 +53,7 @@ describe('Localization', () => {
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ payload, serverURL } = await initPayloadE2E({ ;({ payload, serverURL } = await initPayloadE2E({
config, config,
dirname: __dirname, dirname,
})) }))
url = new AdminUrlUtil(serverURL, localizedPostsSlug) url = new AdminUrlUtil(serverURL, localizedPostsSlug)

View File

@@ -1,6 +1,7 @@
/* eslint-disable jest/require-top-level-describe */ /* eslint-disable jest/require-top-level-describe */
import * as AWS from '@aws-sdk/client-s3' import * as AWS from '@aws-sdk/client-s3'
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { Payload } from '../../packages/payload/src' import type { Payload } from '../../packages/payload/src'
@@ -8,6 +9,8 @@ import { getPayload } from '../../packages/payload/src'
import { describeIfInCIOrHasLocalstack } from '../helpers' import { describeIfInCIOrHasLocalstack } from '../helpers'
import { startMemoryDB } from '../startMemoryDB' import { startMemoryDB } from '../startMemoryDB'
import configPromise from './config' import configPromise from './config'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
let payload: Payload let payload: Payload
@@ -43,7 +46,7 @@ describe('@payloadcms/plugin-cloud-storage', () => {
const upload = await payload.create({ const upload = await payload.create({
collection: 'media', collection: 'media',
data: {}, data: {},
filePath: path.resolve(__dirname, '../uploads/image.png'), filePath: path.resolve(dirname, '../uploads/image.png'),
}) })
expect(upload.id).toBeTruthy() expect(upload.id).toBeTruthy()

View File

@@ -1,11 +1,17 @@
import type { Page } from '@playwright/test' import type { Page } from '@playwright/test'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import path from 'path'
import { fileURLToPath } from 'url'
import type { Page as PayloadPage } from './payload-types' import type { Page as PayloadPage } from './payload-types'
import { AdminUrlUtil } from '../helpers/adminUrlUtil'
import { initPayloadE2E } from '../helpers/configHelpers'
import payload from '../../packages/payload/src' import payload from '../../packages/payload/src'
import { initPageConsoleErrorCatch } from '../helpers' import { initPageConsoleErrorCatch } from '../helpers'
import { AdminUrlUtil } from '../helpers/adminUrlUtil'
import { initPayloadE2E } from '../helpers/configHelpers'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const { beforeAll, describe } = test const { beforeAll, describe } = test
let url: AdminUrlUtil let url: AdminUrlUtil
@@ -16,10 +22,10 @@ let draftChildId: string
let childId: string let childId: string
type Args = { type Args = {
slug: string
title?: string
parent?: string parent?: string
status?: 'published' | 'draft' slug: string
status?: 'draft' | 'published'
title?: string
} }
async function createPage({ async function createPage({
@@ -31,8 +37,8 @@ async function createPage({
return payload.create({ return payload.create({
collection: 'pages', collection: 'pages',
data: { data: {
title: title, title,
slug: slug, slug,
_status: status, _status: status,
parent, parent,
}, },
@@ -41,7 +47,7 @@ async function createPage({
describe('Nested Docs Plugin', () => { describe('Nested Docs Plugin', () => {
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
const { serverURL } = await initPayloadE2E(__dirname) const { serverURL } = await initPayloadE2E(dirname)
url = new AdminUrlUtil(serverURL, 'pages') url = new AdminUrlUtil(serverURL, 'pages')
const context = await browser.newContext() const context = await browser.newContext()

View File

@@ -1,13 +1,16 @@
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { CollectionConfig } from '../../../packages/payload/src/collections/config/types' import type { CollectionConfig } from '../../../packages/payload/src/collections/config/types'
import { mediaSlug } from '../shared' import { mediaSlug } from '../shared'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
export const Media: CollectionConfig = { export const Media: CollectionConfig = {
slug: mediaSlug, slug: mediaSlug,
upload: { upload: {
staticDir: path.resolve(__dirname, '../media'), staticDir: path.resolve(dirname, '../media'),
}, },
fields: [ fields: [
{ {

View File

@@ -3,6 +3,7 @@ import type { Payload } from 'payload'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { Page as PayloadPage } from './payload-types' import type { Page as PayloadPage } from './payload-types'
@@ -12,6 +13,8 @@ import { AdminUrlUtil } from '../helpers/adminUrlUtil'
import { initPayloadE2E } from '../helpers/configHelpers' import { initPayloadE2E } from '../helpers/configHelpers'
import config from '../uploads/config' import config from '../uploads/config'
import { mediaSlug } from './shared' import { mediaSlug } from './shared'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const { beforeAll, describe } = test const { beforeAll, describe } = test
let url: AdminUrlUtil let url: AdminUrlUtil
@@ -21,14 +24,14 @@ let payload: Payload
describe('SEO Plugin', () => { describe('SEO Plugin', () => {
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
const { serverURL } = await initPayloadE2E({ config, dirname: __dirname }) const { serverURL } = await initPayloadE2E({ config, dirname })
url = new AdminUrlUtil(serverURL, 'pages') url = new AdminUrlUtil(serverURL, 'pages')
const context = await browser.newContext() const context = await browser.newContext()
page = await context.newPage() page = await context.newPage()
initPageConsoleErrorCatch(page) initPageConsoleErrorCatch(page)
const filePath = path.resolve(__dirname, './image-1.jpg') const filePath = path.resolve(dirname, './image-1.jpg')
const file = await getFileByPath(filePath) const file = await getFileByPath(filePath)
const mediaDoc = await payload.create({ const mediaDoc = await payload.create({

View File

@@ -1,4 +1,5 @@
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { Payload } from '../../packages/payload/src' import type { Payload } from '../../packages/payload/src'
@@ -8,6 +9,8 @@ import removeFiles from '../helpers/removeFiles'
import { startMemoryDB } from '../startMemoryDB' import { startMemoryDB } from '../startMemoryDB'
import configPromise from './config' import configPromise from './config'
import { mediaSlug } from './shared' import { mediaSlug } from './shared'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
let payload: Payload let payload: Payload
@@ -16,14 +19,14 @@ describe('@payloadcms/plugin-seo', () => {
let mediaDoc = null let mediaDoc = null
beforeAll(async () => { beforeAll(async () => {
const uploadsDir = path.resolve(__dirname, './media') const uploadsDir = path.resolve(dirname, './media')
removeFiles(path.normalize(uploadsDir)) removeFiles(path.normalize(uploadsDir))
const config = await startMemoryDB(configPromise) const config = await startMemoryDB(configPromise)
payload = await getPayload({ config }) payload = await getPayload({ config })
// Create image // Create image
const filePath = path.resolve(__dirname, './image-1.jpg') const filePath = path.resolve(dirname, './image-1.jpg')
const file = await getFileByPath(filePath) const file = await getFileByPath(filePath)
mediaDoc = await payload.create({ mediaDoc = await payload.create({

View File

@@ -1,10 +1,14 @@
import type { Page } from '@playwright/test' import type { Page } from '@playwright/test'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import path from 'path'
import { fileURLToPath } from 'url'
import { closeNav, initPageConsoleErrorCatch, openNav } from '../helpers' import { closeNav, initPageConsoleErrorCatch, openNav } from '../helpers'
import { initPayloadE2E } from '../helpers/configHelpers' import { initPayloadE2E } from '../helpers/configHelpers'
import config from './config' import config from './config'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const { beforeAll, describe } = test const { beforeAll, describe } = test
@@ -13,7 +17,7 @@ describe('refresh-permissions', () => {
let page: Page let page: Page
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ serverURL } = await initPayloadE2E({ config, dirname: __dirname })) ;({ serverURL } = await initPayloadE2E({ config, dirname }))
const context = await browser.newContext() const context = await browser.newContext()
page = await context.newPage() page = await context.newPage()

View File

@@ -6,11 +6,11 @@ import slash from 'slash'
import { fileURLToPath } from 'url' import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url) const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename) const dirname = path.dirname(__filename)
shelljs.env.DISABLE_LOGGING = 'true' shelljs.env.DISABLE_LOGGING = 'true'
const playwrightBin = path.resolve(__dirname, '../node_modules/.bin/playwright') const playwrightBin = path.resolve(dirname, '../node_modules/.bin/playwright')
const testRunCodes: { code: number; suiteName: string }[] = [] const testRunCodes: { code: number; suiteName: string }[] = []
const { _: args, bail, part } = minimist(process.argv.slice(2)) const { _: args, bail, part } = minimist(process.argv.slice(2))
@@ -18,7 +18,7 @@ const suiteName = args[0]
// Run all // Run all
if (!suiteName) { if (!suiteName) {
let files = glob.sync(`${path.resolve(__dirname).replace(/\\/g, '/')}/**/*e2e.spec.ts`) let files = glob.sync(`${path.resolve(dirname).replace(/\\/g, '/')}/**/*e2e.spec.ts`)
const totalFiles = files.length const totalFiles = files.length
@@ -53,7 +53,7 @@ if (!suiteName) {
} else { } else {
// Run specific suite // Run specific suite
clearWebpackCache() clearWebpackCache()
const suitePath = path.resolve(__dirname, suiteName, 'e2e.spec.ts') const suitePath = path.resolve(dirname, suiteName, 'e2e.spec.ts')
executePlaywright(suitePath) executePlaywright(suitePath)
} }
@@ -68,7 +68,7 @@ if (testRunCodes.some((tr) => tr.code > 0)) process.exit(1)
function executePlaywright(suitePath: string, bail = false) { function executePlaywright(suitePath: string, bail = false) {
console.log(`Executing ${suitePath}...`) console.log(`Executing ${suitePath}...`)
const playwrightCfg = path.resolve( const playwrightCfg = path.resolve(
__dirname, dirname,
'..', '..',
`${bail ? 'playwright.bail.config.ts' : 'playwright.config.ts'}`, `${bail ? 'playwright.bail.config.ts' : 'playwright.config.ts'}`,
) )
@@ -89,6 +89,6 @@ function executePlaywright(suitePath: string, bail = false) {
} }
function clearWebpackCache() { function clearWebpackCache() {
const webpackCachePath = path.resolve(__dirname, '../node_modules/.cache/webpack') const webpackCachePath = path.resolve(dirname, '../node_modules/.cache/webpack')
shelljs.rm('-rf', webpackCachePath) shelljs.rm('-rf', webpackCachePath)
} }

View File

@@ -3,6 +3,7 @@ import type { Payload } from 'payload'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import type { Media } from './payload-types' import type { Media } from './payload-types'
@@ -14,6 +15,8 @@ import { RESTClient } from '../helpers/rest'
import { adminThumbnailSrc } from './collections/admin-thumbnail' import { adminThumbnailSrc } from './collections/admin-thumbnail'
import config from './config' import config from './config'
import { adminThumbnailSlug, audioSlug, mediaSlug, relationSlug } from './shared' import { adminThumbnailSlug, audioSlug, mediaSlug, relationSlug } from './shared'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const { beforeAll, describe } = test const { beforeAll, describe } = test
@@ -31,7 +34,7 @@ describe('uploads', () => {
let audioDoc: Media let audioDoc: Media
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ payload, serverURL } = await initPayloadE2E({ config, dirname: __dirname })) ;({ payload, serverURL } = await initPayloadE2E({ config, dirname }))
client = new RESTClient(null, { defaultSlug: 'users', serverURL }) client = new RESTClient(null, { defaultSlug: 'users', serverURL })
await client.login() await client.login()
@@ -88,7 +91,7 @@ describe('uploads', () => {
test('should create file upload', async () => { test('should create file upload', async () => {
await page.goto(mediaURL.create) await page.goto(mediaURL.create)
await page.setInputFiles('input[type="file"]', path.resolve(__dirname, './image.png')) await page.setInputFiles('input[type="file"]', path.resolve(dirname, './image.png'))
const filename = page.locator('.file-field__filename') const filename = page.locator('.file-field__filename')
@@ -201,7 +204,7 @@ describe('uploads', () => {
await expect(page.locator('[id^=doc-drawer_media_2_]')).toBeVisible() await expect(page.locator('[id^=doc-drawer_media_2_]')).toBeVisible()
await page await page
.locator('[id^=doc-drawer_media_2_] .file-field__upload input[type="file"]') .locator('[id^=doc-drawer_media_2_] .file-field__upload input[type="file"]')
.setInputFiles(path.resolve(__dirname, './image.png')) .setInputFiles(path.resolve(dirname, './image.png'))
await page.locator('[id^=doc-drawer_media_2_] button#action-save').click() await page.locator('[id^=doc-drawer_media_2_] button#action-save').click()
await wait(200) await wait(200)
await expect(page.locator('.Toastify')).toContainText('successfully') await expect(page.locator('.Toastify')).toContainText('successfully')
@@ -227,7 +230,7 @@ describe('uploads', () => {
test('Should detect correct mimeType', async () => { test('Should detect correct mimeType', async () => {
await page.goto(mediaURL.create) await page.goto(mediaURL.create)
await page.setInputFiles('input[type="file"]', path.resolve(__dirname, './image.png')) await page.setInputFiles('input[type="file"]', path.resolve(dirname, './image.png'))
await saveDocAndAssert(page) await saveDocAndAssert(page)
const imageID = page.url().split('/').pop() const imageID = page.url().split('/').pop()
@@ -265,7 +268,7 @@ describe('uploads', () => {
const fileChooserPromise = page.waitForEvent('filechooser') const fileChooserPromise = page.waitForEvent('filechooser')
await page.getByText('Select a file').click() await page.getByText('Select a file').click()
const fileChooser = await fileChooserPromise const fileChooser = await fileChooserPromise
await fileChooser.setFiles(path.join(__dirname, 'test-image.jpg')) await fileChooser.setFiles(path.join(dirname, 'test-image.jpg'))
await page.locator('.file-field__edit').click() await page.locator('.file-field__edit').click()
// set crop // set crop

View File

@@ -2,6 +2,7 @@ import { File as FileBuffer } from 'buffer'
import NodeFormData from 'form-data' import NodeFormData from 'form-data'
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
import { promisify } from 'util' import { promisify } from 'util'
import type { Payload } from '../../packages/payload/src' import type { Payload } from '../../packages/payload/src'
@@ -20,6 +21,8 @@ import {
unstoredMediaSlug, unstoredMediaSlug,
usersSlug, usersSlug,
} from './shared' } from './shared'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const getMimeType = ( const getMimeType = (
filePath: string, filePath: string,
@@ -64,7 +67,7 @@ const bufferToFileBlob = async (filePath: string): Promise<File> =>
// Convert type FileBuffer > unknown > File // Convert type FileBuffer > unknown > File
// The File type expects webkitRelativePath, we don't have that // The File type expects webkitRelativePath, we don't have that
resolve(new FileBuffer([data], filename, { type: type }) as unknown as File) resolve(new FileBuffer([data], filename, { type }) as unknown as File)
}) })
}) })
@@ -85,7 +88,7 @@ describe('Collections - Uploads', () => {
describe('create', () => { describe('create', () => {
it('creates from form data given a png', async () => { it('creates from form data given a png', async () => {
const formData = new FormData() const formData = new FormData()
const filePath = path.join(__dirname, './image.png') const filePath = path.join(dirname, './image.png')
formData.append('file', await bufferToFileBlob(filePath)) formData.append('file', await bufferToFileBlob(filePath))
@@ -98,7 +101,7 @@ describe('Collections - Uploads', () => {
expect(response.status).toBe(201) expect(response.status).toBe(201)
const { sizes } = doc const { sizes } = doc
const expectedPath = path.join(__dirname, './media') const expectedPath = path.join(dirname, './media')
// Check for files // Check for files
expect(await fileExists(path.join(expectedPath, doc.filename))).toBe(true) expect(await fileExists(path.join(expectedPath, doc.filename))).toBe(true)
@@ -122,7 +125,7 @@ describe('Collections - Uploads', () => {
it('creates from form data given an svg', async () => { it('creates from form data given an svg', async () => {
const formData = new FormData() const formData = new FormData()
const filePath = path.join(__dirname, './image.svg') const filePath = path.join(dirname, './image.svg')
formData.append('file', await bufferToFileBlob(filePath)) formData.append('file', await bufferToFileBlob(filePath))
const response = await restClient.POST(`/${mediaSlug}`, { const response = await restClient.POST(`/${mediaSlug}`, {
@@ -134,7 +137,7 @@ describe('Collections - Uploads', () => {
expect(response.status).toBe(201) expect(response.status).toBe(201)
// Check for files // Check for files
expect(await fileExists(path.join(__dirname, './media', doc.filename))).toBe(true) expect(await fileExists(path.join(dirname, './media', doc.filename))).toBe(true)
// Check api response // Check api response
expect(doc.mimeType).toEqual('image/svg+xml') expect(doc.mimeType).toEqual('image/svg+xml')
@@ -146,7 +149,7 @@ describe('Collections - Uploads', () => {
it('should have valid image url', async () => { it('should have valid image url', async () => {
const formData = new FormData() const formData = new FormData()
const fileBlob = await bufferToFileBlob(path.join(__dirname, './image.svg')) const fileBlob = await bufferToFileBlob(path.join(dirname, './image.svg'))
formData.append('file', fileBlob) formData.append('file', fileBlob)
const response = await restClient.POST(`/${mediaSlug}`, { const response = await restClient.POST(`/${mediaSlug}`, {
@@ -156,7 +159,7 @@ describe('Collections - Uploads', () => {
const { doc } = await response.json() const { doc } = await response.json()
expect(response.status).toBe(201) expect(response.status).toBe(201)
const expectedPath = path.join(__dirname, './media') const expectedPath = path.join(dirname, './media')
expect(await fileExists(path.join(expectedPath, doc.filename))).toBe(true) expect(await fileExists(path.join(expectedPath, doc.filename))).toBe(true)
expect(doc.url).not.toContain('undefined') expect(doc.url).not.toContain('undefined')
@@ -164,7 +167,7 @@ describe('Collections - Uploads', () => {
it('creates images that do not require all sizes', async () => { it('creates images that do not require all sizes', async () => {
const formData = new FormData() const formData = new FormData()
const fileBlob = await bufferToFileBlob(path.join(__dirname, './small.png')) const fileBlob = await bufferToFileBlob(path.join(dirname, './small.png'))
formData.append('file', fileBlob) formData.append('file', fileBlob)
const response = await restClient.POST(`/${mediaSlug}`, { const response = await restClient.POST(`/${mediaSlug}`, {
@@ -175,7 +178,7 @@ describe('Collections - Uploads', () => {
expect(response.status).toBe(201) expect(response.status).toBe(201)
const expectedPath = path.join(__dirname, './media') const expectedPath = path.join(dirname, './media')
// Check for files // Check for files
expect(await fileExists(path.join(expectedPath, doc.filename))).toBe(true) expect(await fileExists(path.join(expectedPath, doc.filename))).toBe(true)
@@ -189,7 +192,7 @@ describe('Collections - Uploads', () => {
it('creates images from a different format', async () => { it('creates images from a different format', async () => {
const formData = new FormData() const formData = new FormData()
const fileBlob = await bufferToFileBlob(path.join(__dirname, './image.jpg')) const fileBlob = await bufferToFileBlob(path.join(dirname, './image.jpg'))
formData.append('file', fileBlob) formData.append('file', fileBlob)
const response = await restClient.POST(`/${mediaSlug}`, { const response = await restClient.POST(`/${mediaSlug}`, {
@@ -200,7 +203,7 @@ describe('Collections - Uploads', () => {
expect(response.status).toBe(201) expect(response.status).toBe(201)
const expectedPath = path.join(__dirname, './media') const expectedPath = path.join(dirname, './media')
// Check for files // Check for files
expect(await fileExists(path.join(expectedPath, doc.filename))).toBe(true) expect(await fileExists(path.join(expectedPath, doc.filename))).toBe(true)
@@ -217,7 +220,7 @@ describe('Collections - Uploads', () => {
it('creates media without storing a file', async () => { it('creates media without storing a file', async () => {
const formData = new FormData() const formData = new FormData()
const fileBlob = await bufferToFileBlob(path.join(__dirname, './unstored.png')) const fileBlob = await bufferToFileBlob(path.join(dirname, './unstored.png'))
formData.append('file', fileBlob) formData.append('file', fileBlob)
// unstored media // unstored media
@@ -230,14 +233,14 @@ describe('Collections - Uploads', () => {
expect(response.status).toBe(201) expect(response.status).toBe(201)
// Check for files // Check for files
expect(await fileExists(path.join(__dirname, './media', doc.filename))).toBe(false) expect(await fileExists(path.join(dirname, './media', doc.filename))).toBe(false)
// Check api response // Check api response
expect(doc.filename).toBeDefined() expect(doc.filename).toBeDefined()
}) })
it('should enlarge images if resize options `withoutEnlargement` is set to false', async () => { it('should enlarge images if resize options `withoutEnlargement` is set to false', async () => {
const small = await getFileByPath(path.resolve(__dirname, './small.png')) const small = await getFileByPath(path.resolve(dirname, './small.png'))
const result = await payload.create({ const result = await payload.create({
collection: enlargeSlug, collection: enlargeSlug,
@@ -248,7 +251,7 @@ describe('Collections - Uploads', () => {
expect(result).toBeTruthy() expect(result).toBeTruthy()
const { sizes } = result as unknown as Enlarge const { sizes } = result as unknown as Enlarge
const expectedPath = path.join(__dirname, './media/enlarge') const expectedPath = path.join(dirname, './media/enlarge')
// Check for files // Check for files
expect(await fileExists(path.join(expectedPath, small.name))).toBe(true) expect(await fileExists(path.join(expectedPath, small.name))).toBe(true)
@@ -282,7 +285,7 @@ describe('Collections - Uploads', () => {
// This test makes sure that the image resizing is not prevented if only one dimension is larger (due to payload preventing enlargement by default) // This test makes sure that the image resizing is not prevented if only one dimension is larger (due to payload preventing enlargement by default)
it('should resize images if one desired dimension is smaller and the other is larger', async () => { it('should resize images if one desired dimension is smaller and the other is larger', async () => {
const small = await getFileByPath(path.resolve(__dirname, './small.png')) const small = await getFileByPath(path.resolve(dirname, './small.png'))
const result = (await payload.create({ const result = (await payload.create({
collection: enlargeSlug, collection: enlargeSlug,
@@ -293,7 +296,7 @@ describe('Collections - Uploads', () => {
expect(result).toBeTruthy() expect(result).toBeTruthy()
const { sizes } = result const { sizes } = result
const expectedPath = path.join(__dirname, './media/enlarge') const expectedPath = path.join(dirname, './media/enlarge')
// Check for files // Check for files
expect(await fileExists(path.join(expectedPath, sizes.widthLowerHeightLarger.filename))).toBe( expect(await fileExists(path.join(expectedPath, sizes.widthLowerHeightLarger.filename))).toBe(
@@ -310,8 +313,8 @@ describe('Collections - Uploads', () => {
it('should not reduce images if resize options `withoutReduction` is set to true', async () => { it('should not reduce images if resize options `withoutReduction` is set to true', async () => {
const formData = new NodeFormData() const formData = new NodeFormData()
formData.append('file', fs.createReadStream(path.join(__dirname, './small.png'))) formData.append('file', fs.createReadStream(path.join(dirname, './small.png')))
const small = await getFileByPath(path.resolve(__dirname, './small.png')) const small = await getFileByPath(path.resolve(dirname, './small.png'))
const result = await payload.create({ const result = await payload.create({
collection: reduceSlug, collection: reduceSlug,
@@ -322,7 +325,7 @@ describe('Collections - Uploads', () => {
expect(result).toBeTruthy() expect(result).toBeTruthy()
const { sizes } = result as unknown as Enlarge const { sizes } = result as unknown as Enlarge
const expectedPath = path.join(__dirname, './media/reduce') const expectedPath = path.join(dirname, './media/reduce')
// Check for files // Check for files
expect(await fileExists(path.join(expectedPath, small.name))).toBe(true) expect(await fileExists(path.join(expectedPath, small.name))).toBe(true)
@@ -352,7 +355,7 @@ describe('Collections - Uploads', () => {
it('update', async () => { it('update', async () => {
// Create image // Create image
const filePath = path.resolve(__dirname, './image.png') const filePath = path.resolve(dirname, './image.png')
const file = await getFileByPath(filePath) const file = await getFileByPath(filePath)
file.name = 'renamed.png' file.name = 'renamed.png'
@@ -363,7 +366,7 @@ describe('Collections - Uploads', () => {
})) as unknown as Media })) as unknown as Media
const formData = new FormData() const formData = new FormData()
formData.append('file', await bufferToFileBlob(path.join(__dirname, './small.png'))) formData.append('file', await bufferToFileBlob(path.join(dirname, './small.png')))
const response = await restClient.PATCH(`/${mediaSlug}/${mediaDoc.id}`, { const response = await restClient.PATCH(`/${mediaSlug}/${mediaDoc.id}`, {
body: formData, body: formData,
@@ -372,7 +375,7 @@ describe('Collections - Uploads', () => {
expect(response.status).toBe(200) expect(response.status).toBe(200)
const expectedPath = path.join(__dirname, './media') const expectedPath = path.join(dirname, './media')
// Check that previously existing files were removed // Check that previously existing files were removed
expect(await fileExists(path.join(expectedPath, mediaDoc.filename))).toBe(false) expect(await fileExists(path.join(expectedPath, mediaDoc.filename))).toBe(false)
@@ -381,7 +384,7 @@ describe('Collections - Uploads', () => {
it('update - update many', async () => { it('update - update many', async () => {
// Create image // Create image
const filePath = path.resolve(__dirname, './image.png') const filePath = path.resolve(dirname, './image.png')
const file = await getFileByPath(filePath) const file = await getFileByPath(filePath)
file.name = 'renamed.png' file.name = 'renamed.png'
@@ -392,7 +395,7 @@ describe('Collections - Uploads', () => {
})) as unknown as Media })) as unknown as Media
const formData = new FormData() const formData = new FormData()
formData.append('file', await bufferToFileBlob(path.join(__dirname, './small.png'))) formData.append('file', await bufferToFileBlob(path.join(dirname, './small.png')))
const response = await restClient.PATCH(`/${mediaSlug}`, { const response = await restClient.PATCH(`/${mediaSlug}`, {
body: formData, body: formData,
@@ -408,7 +411,7 @@ describe('Collections - Uploads', () => {
expect(response.status).toBe(200) expect(response.status).toBe(200)
const expectedPath = path.join(__dirname, './media') const expectedPath = path.join(dirname, './media')
// Check that previously existing files were removed // Check that previously existing files were removed
expect(await fileExists(path.join(expectedPath, mediaDoc.filename))).toBe(false) expect(await fileExists(path.join(expectedPath, mediaDoc.filename))).toBe(false)
@@ -417,7 +420,7 @@ describe('Collections - Uploads', () => {
it('should remove existing media on re-upload', async () => { it('should remove existing media on re-upload', async () => {
// Create temp file // Create temp file
const filePath = path.resolve(__dirname, './temp.png') const filePath = path.resolve(dirname, './temp.png')
const file = await getFileByPath(filePath) const file = await getFileByPath(filePath)
file.name = 'temp.png' file.name = 'temp.png'
@@ -427,13 +430,13 @@ describe('Collections - Uploads', () => {
file, file,
})) as unknown as Media })) as unknown as Media
const expectedPath = path.join(__dirname, './media') const expectedPath = path.join(dirname, './media')
// Check that the temp file was created // Check that the temp file was created
expect(await fileExists(path.join(expectedPath, mediaDoc.filename))).toBe(true) expect(await fileExists(path.join(expectedPath, mediaDoc.filename))).toBe(true)
// Replace the temp file with a new one // Replace the temp file with a new one
const newFilePath = path.resolve(__dirname, './temp-renamed.png') const newFilePath = path.resolve(dirname, './temp-renamed.png')
const newFile = await getFileByPath(newFilePath) const newFile = await getFileByPath(newFilePath)
newFile.name = 'temp-renamed.png' newFile.name = 'temp-renamed.png'
@@ -451,7 +454,7 @@ describe('Collections - Uploads', () => {
it('should remove existing media on re-upload - update many', async () => { it('should remove existing media on re-upload - update many', async () => {
// Create temp file // Create temp file
const filePath = path.resolve(__dirname, './temp.png') const filePath = path.resolve(dirname, './temp.png')
const file = await getFileByPath(filePath) const file = await getFileByPath(filePath)
file.name = 'temp.png' file.name = 'temp.png'
@@ -461,13 +464,13 @@ describe('Collections - Uploads', () => {
file, file,
})) as unknown as Media })) as unknown as Media
const expectedPath = path.join(__dirname, './media') const expectedPath = path.join(dirname, './media')
// Check that the temp file was created // Check that the temp file was created
expect(await fileExists(path.join(expectedPath, mediaDoc.filename))).toBe(true) expect(await fileExists(path.join(expectedPath, mediaDoc.filename))).toBe(true)
// Replace the temp file with a new one // Replace the temp file with a new one
const newFilePath = path.resolve(__dirname, './temp-renamed.png') const newFilePath = path.resolve(dirname, './temp-renamed.png')
const newFile = await getFileByPath(newFilePath) const newFile = await getFileByPath(newFilePath)
newFile.name = 'temp-renamed-second.png' newFile.name = 'temp-renamed-second.png'
@@ -487,9 +490,9 @@ describe('Collections - Uploads', () => {
}) })
it('should remove extra sizes on update', async () => { it('should remove extra sizes on update', async () => {
const filePath = path.resolve(__dirname, './image.png') const filePath = path.resolve(dirname, './image.png')
const file = await getFileByPath(filePath) const file = await getFileByPath(filePath)
const small = await getFileByPath(path.resolve(__dirname, './small.png')) const small = await getFileByPath(path.resolve(dirname, './small.png'))
const { id } = await payload.create({ const { id } = await payload.create({
collection: mediaSlug, collection: mediaSlug,
@@ -509,9 +512,9 @@ describe('Collections - Uploads', () => {
}) })
it('should remove extra sizes on update - update many', async () => { it('should remove extra sizes on update - update many', async () => {
const filePath = path.resolve(__dirname, './image.png') const filePath = path.resolve(dirname, './image.png')
const file = await getFileByPath(filePath) const file = await getFileByPath(filePath)
const small = await getFileByPath(path.resolve(__dirname, './small.png')) const small = await getFileByPath(path.resolve(dirname, './small.png'))
const { id } = await payload.create({ const { id } = await payload.create({
collection: mediaSlug, collection: mediaSlug,
@@ -533,7 +536,7 @@ describe('Collections - Uploads', () => {
}) })
it('should allow update removing a relationship', async () => { it('should allow update removing a relationship', async () => {
const filePath = path.resolve(__dirname, './image.png') const filePath = path.resolve(dirname, './image.png')
const file = await getFileByPath(filePath) const file = await getFileByPath(filePath)
file.name = 'renamed.png' file.name = 'renamed.png'
@@ -562,7 +565,7 @@ describe('Collections - Uploads', () => {
}) })
it('should allow update removing a relationship - update many', async () => { it('should allow update removing a relationship - update many', async () => {
const filePath = path.resolve(__dirname, './image.png') const filePath = path.resolve(dirname, './image.png')
const file = await getFileByPath(filePath) const file = await getFileByPath(filePath)
file.name = 'renamed.png' file.name = 'renamed.png'
@@ -594,7 +597,7 @@ describe('Collections - Uploads', () => {
it('delete', async () => { it('delete', async () => {
const formData = new FormData() const formData = new FormData()
formData.append('file', await bufferToFileBlob(path.join(__dirname, './image.png'))) formData.append('file', await bufferToFileBlob(path.join(dirname, './image.png')))
const { doc } = await restClient const { doc } = await restClient
.POST(`/${mediaSlug}`, { .POST(`/${mediaSlug}`, {
@@ -606,12 +609,12 @@ describe('Collections - Uploads', () => {
const response2 = await restClient.DELETE(`/${mediaSlug}/${doc.id}`) const response2 = await restClient.DELETE(`/${mediaSlug}/${doc.id}`)
expect(response2.status).toBe(200) expect(response2.status).toBe(200)
expect(await fileExists(path.join(__dirname, doc.filename))).toBe(false) expect(await fileExists(path.join(dirname, doc.filename))).toBe(false)
}) })
it('delete - update many', async () => { it('delete - update many', async () => {
const formData = new FormData() const formData = new FormData()
formData.append('file', await bufferToFileBlob(path.join(__dirname, './image.png'))) formData.append('file', await bufferToFileBlob(path.join(dirname, './image.png')))
const { doc } = await restClient const { doc } = await restClient
.POST(`/${mediaSlug}`, { .POST(`/${mediaSlug}`, {
@@ -634,7 +637,7 @@ describe('Collections - Uploads', () => {
expect(errors).toHaveLength(0) expect(errors).toHaveLength(0)
expect(await fileExists(path.join(__dirname, doc.filename))).toBe(false) expect(await fileExists(path.join(dirname, doc.filename))).toBe(false)
}) })
describe('filesRequiredOnCreate', () => { describe('filesRequiredOnCreate', () => {
@@ -643,7 +646,7 @@ describe('Collections - Uploads', () => {
expect( expect(
async () => async () =>
await payload.create({ await payload.create({
// @ts-ignore // @ts-expect-error
collection: 'optional-file', collection: 'optional-file',
data: {}, data: {},
}), }),
@@ -653,7 +656,7 @@ describe('Collections - Uploads', () => {
it('should throw an error if no file and filesRequiredOnCreate is true', async () => { it('should throw an error if no file and filesRequiredOnCreate is true', async () => {
await expect(async () => await expect(async () =>
payload.create({ payload.create({
// @ts-ignore // @ts-expect-error
collection: 'required-file', collection: 'required-file',
data: {}, data: {},
}), }),

View File

@@ -27,6 +27,8 @@ import type { Page } from '@playwright/test'
import type { Payload } from 'payload' import type { Payload } from 'payload'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import path from 'path'
import { fileURLToPath } from 'url'
import wait from '../../packages/payload/src/utilities/wait' import wait from '../../packages/payload/src/utilities/wait'
import { globalSlug } from '../admin/slugs' import { globalSlug } from '../admin/slugs'
@@ -52,6 +54,8 @@ import {
draftGlobalSlug, draftGlobalSlug,
postCollectionSlug, postCollectionSlug,
} from './slugs' } from './slugs'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const { beforeAll, beforeEach, describe } = test const { beforeAll, beforeEach, describe } = test
@@ -67,7 +71,7 @@ describe('versions', () => {
let postURL: AdminUrlUtil let postURL: AdminUrlUtil
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
;({ payload, serverURL } = await initPayloadE2E({ config, dirname: __dirname })) ;({ payload, serverURL } = await initPayloadE2E({ config, dirname }))
const context = await browser.newContext() const context = await browser.newContext()
page = await context.newPage() page = await context.newPage()