chore(examples): remove outdated testing example (#10370)

This deletes the outdated testing example, as it has not been updated to
Payload v3 yet.

We can add it back in the future once we updated it. Generally, the
Next.js testing docs should now be valid:
https://nextjs.org/docs/app/building-your-application/testing. However,
it might still make sense to provide a v3 testing example to showcase
things like booting up an in-memory db
This commit is contained in:
Alessio Gravili
2025-01-05 17:43:53 -07:00
committed by GitHub
parent 8d245283b3
commit 5ba477b810
14 changed files with 0 additions and 9358 deletions

View File

@@ -1,5 +0,0 @@
PORT=3000
MONGO_URL=mongodb://127.0.0.1/your-project-name
PAYLOAD_SECRET_KEY=alwifhjoq284jgo5w34jgo43f3
PAYLOAD_CONFIG_PATH=src/payload.config.ts
PAYLOAD_PUBLIC_SERVER_URL=http://localhost:3000

View File

@@ -1,151 +0,0 @@
# Payload Testing Example
This example demonstrates how to get started with testing Payload using [Jest](https://jestjs.io/). You can clone this down and use it as a starting point for your own Payload projects, or you can follow the steps below to add testing to your existing Payload project.
## Spin up locally:
Run the following command to create a project from the example:
- `npx create-payload-app --example testing`
## Add testing to your existing Payload project
1. Initial setup:
```bash
# install dependencies
yarn add --dev jest mongodb-memory-server @swc/jest @swc/core isomorphic-fetch @types/jest
```
```bash
# create a .env file
cp .env.example .env
```
2. This example uses the following folder structure:
```
root
└─ /src
└─ payload.config.ts
└─ /tests
```
3. Add test credentials to your project. Create a file at `src/tests/credentials.ts` with the following contents:
```ts
export default {
email: 'test@test.com',
password: 'test',
}
```
4. Add the global setup file to your project. This file will be run before any tests are run. It will start a MongoDB server and create a Payload instance for you to use in your tests. Create a file at `src/tests/globalSetup.ts` with the following contents:
```ts
import { resolve } from 'path'
import payload from 'payload'
import express from 'express'
import testCredentials from './credentials'
require('dotenv').config({
path: resolve(__dirname, '../../.env'),
})
const app = express()
const globalSetup = async () => {
await payload.init({
secret: process.env.PAYLOAD_SECRET_KEY,
express: app,
})
app.listen(process.env.PORT, async () => {
console.log(`Express is now listening for incoming connections on port ${process.env.PORT}.`)
})
const response = await fetch(
`${process.env.PAYLOAD_PUBLIC_SERVER_URL}/api/users/first-register`,
{
body: JSON.stringify({
email: testCredentials.email,
password: testCredentials.password,
}),
headers: {
'Content-Type': 'application/json',
},
method: 'post',
},
)
const data = await response.json()
if (!data.user || !data.user.token) {
throw new Error('Failed to register first user')
}
}
export default globalSetup
```
5. Add a `jest.config.ts` file to the root of your project:
```ts
module.exports = {
verbose: true,
globalSetup: '<rootDir>/src/tests/globalSetup.ts',
roots: ['<rootDir>/src/'],
extensionsToTreatAsEsm: ['.ts', '.tsx'],
transform: {
'^.+\\.(t|j)sx?$': [
'@swc/jest',
{
jsc: {
target: 'es2021',
},
},
],
},
}
```
6. Write your first test. Create a file at `src/tests/login.spec.ts` with the following contents:
```ts
import { User } from '../payload-types'
import testCredentials from './credentials'
describe('Users', () => {
it('should allow a user to log in', async () => {
const result: {
token: string
user: User
} = await fetch(`${process.env.PAYLOAD_PUBLIC_SERVER_URL}/api/users/login`, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: testCredentials.email,
password: testCredentials.password,
}),
}).then((res) => res.json())
expect(result.token).toBeDefined()
})
})
```
7. Add a script to run tests via the command line. Add the following to your `package.json` scripts:
```json
"scripts": {
"test": "jest --forceExit --detectOpenHandles"
}
```
8. Run your tests:
```bash
yarn test
```

View File

@@ -1,16 +0,0 @@
module.exports = {
verbose: true,
globalSetup: '<rootDir>/src/tests/globalSetup.ts',
roots: ['<rootDir>/src/'],
extensionsToTreatAsEsm: ['.ts', '.tsx'],
transform: {
'^.+\\.(t|j)sx?$': [
'@swc/jest',
{
jsc: {
target: 'es2021',
},
},
],
},
}

View File

@@ -1,4 +0,0 @@
{
"watch": ["./src/**/*.ts"],
"exec": "ts-node ./src/server.ts -- -I"
}

View File

@@ -1,34 +0,0 @@
{
"name": "jest-payload",
"version": "1.0.0",
"license": "MIT",
"main": "index.js",
"scripts": {
"build": "yarn build:server && yarn build:payload",
"build:payload": "PAYLOAD_CONFIG_PATH=src/payload.config.ts payload build",
"build:server": "tsc",
"dev": "nodemon",
"generate:types": "PAYLOAD_CONFIG_PATH=src/payload.config.ts payload generate:types",
"serve": "PAYLOAD_CONFIG_PATH=dist/payload.config.js NODE_ENV=production node dist/server.js",
"test": "jest --forceExit --detectOpenHandles"
},
"dependencies": {
"@payloadcms/bundler-webpack": "^1.0.5",
"@payloadcms/db-mongodb": "^1.1.0",
"@payloadcms/richtext-slate": "^1.3.1",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"get-tsconfig": "4.8.1",
"payload": "^2.4.0"
},
"devDependencies": {
"@swc/core": "^1.3.84",
"@swc/jest": "^0.2.29",
"@types/jest": "^29.5.4",
"jest": "^29.7.0",
"mongodb-memory-server": "^8.15.1",
"nodemon": "^3.0.1",
"ts-node": "10.9.1",
"typescript": "^5.2.2"
}
}

View File

@@ -1,35 +0,0 @@
/* tslint:disable */
/* eslint-disable */
/**
* This file was automatically generated by Payload.
* DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,
* and re-run `payload generate:types` to regenerate this file.
*/
export interface Config {
collections: {
posts: Post
users: User
}
globals: {}
}
export interface Post {
id: string
title?: string
author?: string | User
updatedAt: string
createdAt: string
}
export interface User {
id: string
updatedAt: string
createdAt: string
email: string
resetPasswordToken?: string
resetPasswordExpiration?: string
salt?: string
hash?: string
loginAttempts?: number
lockUntil?: string
password?: string
}

View File

@@ -1,43 +0,0 @@
import path from 'path'
import dotenv from 'dotenv'
import { buildConfig } from 'payload/config'
import { mongooseAdapter } from '@payloadcms/db-mongodb'
import { slateEditor } from '@payloadcms/richtext-slate'
import { webpackBundler } from '@payloadcms/bundler-webpack'
dotenv.config({
path: path.resolve(__dirname, '../.env'),
})
export default buildConfig({
serverURL: process.env.PAYLOAD_PUBLIC_SERVER_URL,
typescript: {
outputFile: path.resolve(__dirname, 'payload-types.ts'),
},
db: mongooseAdapter({
url: process.env.MONGO_URL,
}),
editor: slateEditor({}),
admin: {
bundler: webpackBundler(),
},
collections: [
{
slug: 'posts',
admin: {
useAsTitle: 'title',
},
fields: [
{
name: 'title',
type: 'text',
},
{
name: 'author',
type: 'relationship',
relationTo: 'users',
},
],
},
],
})

View File

@@ -1,23 +0,0 @@
import path from 'path'
import express from 'express'
import payload from 'payload'
// Use `dotenv` to import your `.env` file automatically
require('dotenv').config({
path: path.resolve(__dirname, '../.env'),
})
const app = express()
async function start() {
await payload.init({
secret: process.env.PAYLOAD_SECRET_KEY,
express: app,
})
app.listen(process.env.PORT, async () => {
console.log(`Express is now listening for incoming connections on port ${process.env.PORT}.`)
})
}
start()

View File

@@ -1,4 +0,0 @@
export default {
email: 'test@test.com',
password: 'test',
}

View File

@@ -1,43 +0,0 @@
import { resolve } from 'path'
import payload from 'payload'
import express from 'express'
import testCredentials from './credentials'
require('dotenv').config({
path: resolve(__dirname, '../../.env'),
})
const app = express()
const globalSetup = async () => {
await payload.init({
secret: process.env.PAYLOAD_SECRET_KEY,
express: app,
})
app.listen(process.env.PORT, async () => {
console.log(`Express is now listening for incoming connections on port ${process.env.PORT}.`)
})
const response = await fetch(
`${process.env.PAYLOAD_PUBLIC_SERVER_URL}/api/users/first-register`,
{
body: JSON.stringify({
email: testCredentials.email,
password: testCredentials.password,
}),
headers: {
'Content-Type': 'application/json',
},
method: 'post',
},
)
const data = await response.json()
if (!data.user || !data.user.token) {
throw new Error('Failed to register first user')
}
}
export default globalSetup

View File

@@ -1,22 +0,0 @@
import { User } from '../payload-types'
import testCredentials from './credentials'
describe('Users', () => {
it('should allow a user to log in', async () => {
const result: {
token: string
user: User
} = await fetch(`${process.env.PAYLOAD_PUBLIC_SERVER_URL}/api/users/login`, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: testCredentials.email,
password: testCredentials.password,
}),
}).then((res) => res.json())
expect(result.token).toBeDefined()
})
})

View File

@@ -1,25 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"DOM",
"DOM.Iterable",
"ES2022"
],
"outDir": "./dist",
"skipLibCheck": true,
"strict": false,
"esModuleInterop": true,
"module": "commonjs",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"sourceMap": true
},
"include": ["src"],
"ts-node": {
"transpileOnly": true
}
}

File diff suppressed because it is too large Load Diff